aboutsummaryrefslogtreecommitdiffstats
path: root/functest/opnfv_tests/vnf/ims
diff options
context:
space:
mode:
Diffstat (limited to 'functest/opnfv_tests/vnf/ims')
-rw-r--r--functest/opnfv_tests/vnf/ims/clearwater_ims_base.py36
-rw-r--r--functest/opnfv_tests/vnf/ims/cloudify_ims.py66
-rw-r--r--functest/opnfv_tests/vnf/ims/cloudify_ims.yaml6
-rw-r--r--functest/opnfv_tests/vnf/ims/opera_ims.py131
-rw-r--r--functest/opnfv_tests/vnf/ims/orchestra.yaml61
-rw-r--r--functest/opnfv_tests/vnf/ims/orchestra_clearwaterims.py682
-rw-r--r--functest/opnfv_tests/vnf/ims/orchestra_ims.py487
-rw-r--r--functest/opnfv_tests/vnf/ims/orchestra_ims.yaml21
-rw-r--r--functest/opnfv_tests/vnf/ims/orchestra_openims.py718
9 files changed, 1521 insertions, 687 deletions
diff --git a/functest/opnfv_tests/vnf/ims/clearwater_ims_base.py b/functest/opnfv_tests/vnf/ims/clearwater_ims_base.py
index 25ddca21..8851f7a4 100644
--- a/functest/opnfv_tests/vnf/ims/clearwater_ims_base.py
+++ b/functest/opnfv_tests/vnf/ims/clearwater_ims_base.py
@@ -10,7 +10,9 @@ import json
import logging
import os
import pkg_resources
+import shlex
import shutil
+import subprocess
import time
import requests
@@ -43,7 +45,7 @@ class ClearwaterOnBoardingBase(vnf.VnfOnBoarding):
def config_ellis(self, ellis_ip, signup_code='secret', two_numbers=False):
output_dict = {}
- self.logger.info('Configure Ellis: %s', ellis_ip)
+ self.logger.debug('Configure Ellis: %s', ellis_ip)
output_dict['ellis_ip'] = ellis_ip
account_url = 'http://{0}/accounts'.format(ellis_ip)
params = {"password": "functest",
@@ -54,7 +56,7 @@ class ClearwaterOnBoardingBase(vnf.VnfOnBoarding):
output_dict['login'] = params
if rq.status_code != 201 and rq.status_code != 409:
raise Exception("Unable to create an account for number provision")
- self.logger.info('Account is created on Ellis: %s', params)
+ self.logger.debug('Account is created on Ellis: %s', params)
session_url = 'http://{0}/session'.format(ellis_ip)
session_data = {
@@ -66,13 +68,13 @@ class ClearwaterOnBoardingBase(vnf.VnfOnBoarding):
if rq.status_code != 201:
raise Exception('Failed to get cookie for Ellis')
cookies = rq.cookies
- self.logger.info('Cookies: %s', cookies)
+ self.logger.debug('Cookies: %s', cookies)
number_url = 'http://{0}/accounts/{1}/numbers'.format(
ellis_ip,
params['email'])
- self.logger.info('Create 1st calling number on Ellis')
- i = 24
+ self.logger.debug('Create 1st calling number on Ellis')
+ i = 30
while rq.status_code != 200 and i > 0:
try:
number_res = self.create_ellis_number(number_url, cookies)
@@ -86,7 +88,7 @@ class ClearwaterOnBoardingBase(vnf.VnfOnBoarding):
output_dict['number'] = number_res
if two_numbers:
- self.logger.info('Create 2nd calling number on Ellis')
+ self.logger.debug('Create 2nd calling number on Ellis')
number_res = self.create_ellis_number(number_url, cookies)
output_dict['number2'] = number_res
@@ -109,19 +111,17 @@ class ClearwaterOnBoardingBase(vnf.VnfOnBoarding):
bono_ip=None, ellis_ip=None,
signup_code='secret'):
self.logger.info('Run Clearwater live test')
- nameservers = ft_utils.get_resolvconf_ns()
- resolvconf = ['{0}{1}{2}'.format(os.linesep, 'nameserver ', ns)
- for ns in nameservers]
- self.logger.debug('resolvconf: %s', resolvconf)
dns_file = '/etc/resolv.conf'
dns_file_bak = '/etc/resolv.conf.bak'
+ self.logger.debug('Backup %s -> %s', dns_file, dns_file_bak)
shutil.copy(dns_file, dns_file_bak)
- script = ('echo -e "nameserver {0}{1}" > {2};'
- 'source /etc/profile.d/rvm.sh;'
- 'cd {3};'
- 'rake test[{4}] SIGNUP_CODE={5}'
- .format(dns_ip,
- ''.join(resolvconf),
+ cmd = ("dnsmasq -d -u root --server=/clearwater.opnfv/{0} "
+ "-r /etc/resolv.conf.bak".format(dns_ip))
+ dnsmasq_process = subprocess.Popen(shlex.split(cmd))
+ script = ('echo -e "nameserver {0}" > {1};'
+ 'cd {2};'
+ 'rake test[{3}] SIGNUP_CODE={4}'
+ .format('127.0.0.1',
dns_file,
self.test_dir,
public_domain,
@@ -131,12 +131,12 @@ class ClearwaterOnBoardingBase(vnf.VnfOnBoarding):
script = '{0}{1}'.format(script, subscript)
script = ('{0}{1}'.format(script, ' --trace'))
cmd = "/bin/bash -c '{0}'".format(script)
- self.logger.info('Live test cmd: %s', cmd)
+ self.logger.debug('Live test cmd: %s', cmd)
output_file = os.path.join(self.result_dir, "ims_test_output.txt")
ft_utils.execute_command(cmd,
error_msg='Clearwater live test failed',
output_file=output_file)
-
+ dnsmasq_process.kill()
with open(dns_file_bak, 'r') as bak_file:
result = bak_file.read()
with open(dns_file, 'w') as f:
diff --git a/functest/opnfv_tests/vnf/ims/cloudify_ims.py b/functest/opnfv_tests/vnf/ims/cloudify_ims.py
index fafc77e1..b07eaee2 100644
--- a/functest/opnfv_tests/vnf/ims/cloudify_ims.py
+++ b/functest/opnfv_tests/vnf/ims/cloudify_ims.py
@@ -1,6 +1,6 @@
#!/usr/bin/env python
-# Copyright (c) 2016 Orange and others.
+# Copyright (c) 2017 Orange and others.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
@@ -25,16 +25,16 @@ from functest.utils.constants import CONST
import functest.utils.openstack_utils as os_utils
from snaps.openstack.os_credentials import OSCreds
-from snaps.openstack.create_network import NetworkSettings, SubnetSettings, \
- OpenStackNetwork
-from snaps.openstack.create_security_group import SecurityGroupSettings, \
- SecurityGroupRuleSettings,\
- Direction, Protocol, \
- OpenStackSecurityGroup
+from snaps.openstack.create_network import (NetworkSettings, SubnetSettings,
+ OpenStackNetwork)
+from snaps.openstack.create_security_group import (SecurityGroupSettings,
+ SecurityGroupRuleSettings,
+ Direction, Protocol,
+ OpenStackSecurityGroup)
from snaps.openstack.create_router import RouterSettings, OpenStackRouter
-from snaps.openstack.create_instance import VmInstanceSettings, \
- FloatingIpSettings, \
- OpenStackVmInstance
+from snaps.openstack.create_instance import (VmInstanceSettings,
+ FloatingIpSettings,
+ OpenStackVmInstance)
from snaps.openstack.create_flavor import FlavorSettings, OpenStackFlavor
from snaps.openstack.create_image import ImageSettings, OpenStackImage
from snaps.openstack.create_keypairs import KeypairSettings, OpenStackKeypair
@@ -110,15 +110,15 @@ class CloudifyIms(clearwater_ims_base.ClearwaterOnBoardingBase):
# needs some images
self.__logger.info("Upload some OS images if it doesn't exist")
- for image_name, image_url in self.images.iteritems():
- self.__logger.info("image: %s, url: %s", image_name, image_url)
- if image_url and image_name:
+ for image_name, image_file in self.images.iteritems():
+ self.__logger.info("image: %s, file: %s", image_name, image_file)
+ if image_file and image_name:
image_creator = OpenStackImage(
self.snaps_creds,
ImageSettings(name=image_name,
image_user='cloud',
img_format='qcow2',
- url=image_url))
+ image_file=image_file))
image_creator.create()
# self.created_object.append(image_creator)
@@ -239,6 +239,8 @@ class CloudifyIms(clearwater_ims_base.ClearwaterOnBoardingBase):
while str(cfy_status) != 'running' and retry:
try:
cfy_status = cfy_client.manager.get_status()['status']
+ self.__logger.debug("The current manager status is %s",
+ cfy_status)
except Exception: # pylint: disable=broad-except
self.__logger.warning("Cloudify Manager isn't " +
"up and running. Retrying ...")
@@ -263,14 +265,15 @@ class CloudifyIms(clearwater_ims_base.ClearwaterOnBoardingBase):
self.__logger.info("Put private keypair in manager")
if manager_creator.vm_ssh_active(block=True):
ssh = manager_creator.ssh_client()
- scp = SCPClient(ssh.get_transport())
+ scp = SCPClient(ssh.get_transport(), socket_timeout=15.0)
scp.put(kp_file, '~/')
cmd = "sudo cp ~/cloudify_ims.pem /etc/cloudify/"
- ssh.exec_command(cmd)
+ run_blocking_ssh_command(ssh, cmd)
cmd = "sudo chmod 444 /etc/cloudify/cloudify_ims.pem"
- ssh.exec_command(cmd)
+ run_blocking_ssh_command(ssh, cmd)
cmd = "sudo yum install -y gcc python-devel"
- ssh.exec_command(cmd)
+ run_blocking_ssh_command(ssh, cmd, "Unable to install packages \
+ on manager")
self.details['orchestrator'].update(status='PASS', duration=duration)
@@ -292,15 +295,17 @@ class CloudifyIms(clearwater_ims_base.ClearwaterOnBoardingBase):
descriptor.get('file_name'))
self.__logger.info("Get or create flavor for all clearwater vm")
- self.exist_obj['flavor2'], flavor_id = os_utils.get_or_create_flavor(
- self.vnf['requirements']['flavor']['name'],
- self.vnf['requirements']['flavor']['ram_min'],
- '30',
- '1',
- public=True)
+ flavor_settings = FlavorSettings(
+ name=self.vnf['requirements']['flavor']['name'],
+ ram=self.vnf['requirements']['flavor']['ram_min'],
+ disk=25,
+ vcpus=1)
+ flavor_creator = OpenStackFlavor(self.snaps_creds, flavor_settings)
+ flavor_creator.create()
+ self.created_object.append(flavor_creator)
self.vnf['inputs'].update(dict(
- flavor_id=flavor_id,
+ flavor_id=self.vnf['requirements']['flavor']['name'],
))
self.__logger.info("Create VNF Instance")
@@ -371,7 +376,7 @@ class CloudifyIms(clearwater_ims_base.ClearwaterOnBoardingBase):
try:
cfy_client.executions.cancel(execution['id'],
force=True)
- except:
+ except: # pylint: disable=broad-except
self.__logger.warn("Can't cancel the current exec")
execution = cfy_client.executions.start(
@@ -383,7 +388,7 @@ class CloudifyIms(clearwater_ims_base.ClearwaterOnBoardingBase):
wait_for_execution(cfy_client, execution, self.__logger)
cfy_client.deployments.delete(self.vnf['descriptor'].get('name'))
cfy_client.blueprints.delete(self.vnf['descriptor'].get('name'))
- except:
+ except: # pylint: disable=broad-except
self.__logger.warn("Some issue during the undeployment ..")
self.__logger.warn("Tenant clean continue ..")
@@ -507,3 +512,10 @@ def sig_test_format(sig_test):
total_sig_test_result['failures'] = nb_failures
total_sig_test_result['skipped'] = nb_skipped
return total_sig_test_result
+
+
+def run_blocking_ssh_command(ssh, cmd, error_msg="Unable to run this command"):
+ """Command to run ssh command with the exit status."""
+ stdin, stdout, stderr = ssh.exec_command(cmd)
+ if stdout.channel.recv_exit_status() != 0:
+ raise Exception(error_msg)
diff --git a/functest/opnfv_tests/vnf/ims/cloudify_ims.yaml b/functest/opnfv_tests/vnf/ims/cloudify_ims.yaml
index f1028ce7..280e0a6b 100644
--- a/functest/opnfv_tests/vnf/ims/cloudify_ims.yaml
+++ b/functest/opnfv_tests/vnf/ims/cloudify_ims.yaml
@@ -1,6 +1,6 @@
tenant_images:
- ubuntu_14.04: http://cloud-images.ubuntu.com/trusty/current/trusty-server-cloudimg-amd64-disk1.img
- cloudify_manager_4.0: http://repository.cloudifysource.org/cloudify/4.0.1/sp-release/cloudify-manager-premium-4.0.1.qcow2
+ ubuntu_14.04: /home/opnfv/functest/images/trusty-server-cloudimg-amd64-disk1.img
+ cloudify_manager_4.0: /home/opnfv/functest/images/cloudify-manager-premium-4.0.1.qcow2
orchestrator:
name: cloudify
version: '4.0'
@@ -19,7 +19,7 @@ vnf:
version: '122'
requirements:
flavor:
- name: m1.medium
+ name: m1.small
ram_min: 2048
inputs:
image_id: 'ubuntu_14.04'
diff --git a/functest/opnfv_tests/vnf/ims/opera_ims.py b/functest/opnfv_tests/vnf/ims/opera_ims.py
deleted file mode 100644
index d420705a..00000000
--- a/functest/opnfv_tests/vnf/ims/opera_ims.py
+++ /dev/null
@@ -1,131 +0,0 @@
-#!/usr/bin/env python
-
-# Copyright (c) 2017 HUAWEI TECHNOLOGIES CO.,LTD and others.
-#
-# All rights reserved. This program and the accompanying materials
-# are made available under the terms of the Apache License, Version 2.0
-# which accompanies this distribution, and is available at
-# http://www.apache.org/licenses/LICENSE-2.0
-
-import json
-import logging
-import os
-import time
-
-from opera import openo_connect
-import requests
-
-import functest.opnfv_tests.vnf.ims.clearwater_ims_base as clearwater_ims_base
-from functest.utils.constants import CONST
-
-
-class OperaIms(clearwater_ims_base.ClearwaterOnBoardingBase):
-
- def __init__(self, **kwargs):
- if "case_name" not in kwargs:
- kwargs["case_name"] = "opera_ims"
- super(OperaIms, self).__init__(**kwargs)
- self.logger = logging.getLogger(__name__)
- self.ellis_file = os.path.join(
- CONST.__getattribute__('dir_results'), 'ellis.info')
- self.live_test_file = os.path.join(
- CONST.__getattribute__('dir_results'), 'live_test_report.json')
- try:
- self.openo_msb_endpoint = os.environ['OPENO_MSB_ENDPOINT']
- except KeyError:
- raise Exception('OPENO_MSB_ENDPOINT is not specified,'
- ' put it as <OPEN-O ip>:<port>')
- else:
- self.logger.info('OPEN-O endpoint is: %s', self.openo_msb_endpoint)
-
- def prepare(self):
- pass
-
- def clean(self):
- pass
-
- def deploy_vnf(self):
- try:
- openo_connect.create_service(self.openo_msb_endpoint,
- 'functest_opera',
- 'VNF for functest testing')
- except Exception as e:
- self.logger.error(e)
- return {'status': 'FAIL', 'result': e}
- else:
- self.logger.info('vIMS deployment is kicked off')
- return {'status': 'PASS', 'result': ''}
-
- def dump_info(self, info_file, result):
- with open(info_file, 'w') as f:
- self.logger.debug('Save information to file: %s', info_file)
- json.dump(result, f)
-
- def test_vnf(self):
- vnfm_ip = openo_connect.get_vnfm_ip(self.openo_msb_endpoint)
- self.logger.info('VNFM IP: %s', vnfm_ip)
- vnf_status_url = 'http://{0}:5000/api/v1/model/status'.format(vnfm_ip)
- vnf_alive = False
- retry = 40
-
- self.logger.info('Check the VNF status')
- while retry > 0:
- rq = requests.get(vnf_status_url, timeout=90)
- response = rq.json()
- vnf_alive = response['vnf_alive']
- msg = response['msg']
- self.logger.info(msg)
- if vnf_alive:
- break
- self.logger.info('check again in one and half a minute...')
- retry = retry - 1
- time.sleep(90)
-
- if not vnf_alive:
- raise Exception('VNF failed to start: {0}'.format(msg))
-
- ellis_config_url = ('http://{0}:5000/api/v1/model/ellis/configure'
- .format(vnfm_ip))
- rq = requests.get(ellis_config_url, timeout=90)
- if rq.json() and not rq.json()['ellis_ok']:
- self.logger.error(rq.json()['data'])
- raise Exception('Failed to configure Ellis')
-
- self.logger.info('Get Clearwater deployment detail')
- vnf_info_url = ('http://{0}:5000/api/v1/model/output'
- .format(vnfm_ip))
- rq = requests.get(vnf_info_url, timeout=90)
- data = rq.json()['data']
- self.logger.info(data)
- bono_ip = data['bono_ip']
- ellis_ip = data['ellis_ip']
- dns_ip = data['dns_ip']
- result = self.config_ellis(ellis_ip, 'signup', True)
- self.logger.debug('Ellis Result: %s', result)
- self.dump_info(self.ellis_file, result)
-
- if dns_ip:
- vims_test_result = self.run_clearwater_live_test(
- dns_ip,
- 'clearwater.local',
- bono_ip,
- ellis_ip,
- 'signup')
- if vims_test_result != '':
- self.dump_info(self.live_test_file, vims_test_result)
- return {'status': 'PASS', 'result': vims_test_result}
- else:
- return {'status': 'FAIL', 'result': ''}
-
- def main(self, **kwargs):
- self.logger.info("Start to run Opera vIMS VNF onboarding test")
- self.execute()
- self.logger.info("Opera vIMS VNF onboarding test finished")
- if self.result is "PASS":
- return self.EX_OK
- else:
- return self.EX_RUN_ERROR
-
- def run(self):
- kwargs = {}
- return self.main(**kwargs)
diff --git a/functest/opnfv_tests/vnf/ims/orchestra.yaml b/functest/opnfv_tests/vnf/ims/orchestra.yaml
new file mode 100644
index 00000000..4cd18e72
--- /dev/null
+++ b/functest/opnfv_tests/vnf/ims/orchestra.yaml
@@ -0,0 +1,61 @@
+tenant_images:
+ orchestrator:
+ ubuntu-14.04-server-cloudimg-amd64-disk1: /home/opnfv/functest/images/trusty-server-cloudimg-amd64-disk1.img
+ orchestra_openims:
+ openims: /home/opnfv/functest/images/img
+ orchestra_clearwaterims:
+ ubuntu-14.04-server-cloudimg-amd64-disk1: /home/opnfv/functest/images/trusty-server-cloudimg-amd64-disk1.img
+mano:
+ name: OpenBaton
+ version: '3.2.0'
+ requirements:
+ flavor:
+ name: openbaton
+ ram_min: 4096
+ disk: 5
+ vcpus: 2
+ image: 'ubuntu-14.04-server-cloudimg-amd64-disk1'
+ bootstrap:
+ url: http://get.openbaton.org/bootstraps/bootstrap_3.2.0_opnfv/bootstrap
+ config:
+ url: http://get.openbaton.org/bootstraps/bootstrap_3.2.0_opnfv/bootstrap-config-file
+ gvnfm:
+ userdata:
+ url: https://raw.githubusercontent.com/openbaton/generic-vnfm/3.2.0/src/main/resources/user-data.sh
+ credentials:
+ username: admin
+ password: openbaton
+
+orchestra_openims:
+ name: OpenIMS
+ descriptor:
+ url: http://marketplace.openbaton.org:8082/api/v1/nsds/fokus/OpenImsCore/3.2.0/json
+ requirements:
+ flavor:
+ name: m1.small
+ ram_min: 2048
+ disk: 5
+ vcpus: 2
+ test:
+ scscf:
+ ports: [3870, 6060]
+ pcscf:
+ ports: [4060]
+ icscf:
+ ports: [3869, 5060]
+ fhoss:
+ ports: [3868]
+ bind9:
+ ports: []
+
+orchestra_clearwaterims:
+ name: Clearwater IMS
+ descriptor:
+ url: http://marketplace.openbaton.org:8082/api/v1/nsds/fokus/ClearwaterIMS/3.2.0/json
+ requirements:
+ flavor:
+ name: m1.small
+ ram_min: 2048
+ disk: 5
+ vcpus: 2
+ test:
diff --git a/functest/opnfv_tests/vnf/ims/orchestra_clearwaterims.py b/functest/opnfv_tests/vnf/ims/orchestra_clearwaterims.py
new file mode 100644
index 00000000..a5405996
--- /dev/null
+++ b/functest/opnfv_tests/vnf/ims/orchestra_clearwaterims.py
@@ -0,0 +1,682 @@
+#!/usr/bin/env python
+
+# Copyright (c) 2016 Orange and others.
+#
+# All rights reserved. This program and the accompanying materials
+# are made available under the terms of the Apache License, Version 2.0
+# which accompanies this distribution, and is available at
+# http://www.apache.org/licenses/LICENSE-2.0
+
+"""Orchestra Clearwater IMS testcase implementation."""
+
+import json
+import logging
+import os
+import socket
+import time
+import pkg_resources
+import yaml
+
+from snaps.openstack.create_image import OpenStackImage, ImageSettings
+from snaps.openstack.create_flavor import OpenStackFlavor, FlavorSettings
+from snaps.openstack.create_security_group import (
+ OpenStackSecurityGroup,
+ SecurityGroupSettings,
+ SecurityGroupRuleSettings,
+ Direction,
+ Protocol)
+from snaps.openstack.create_network import (
+ OpenStackNetwork,
+ NetworkSettings,
+ SubnetSettings,
+ PortSettings)
+from snaps.openstack.create_router import OpenStackRouter, RouterSettings
+from snaps.openstack.os_credentials import OSCreds
+from snaps.openstack.create_instance import (
+ VmInstanceSettings,
+ OpenStackVmInstance)
+from functest.opnfv_tests.openstack.snaps import snaps_utils
+
+import functest.core.vnf as vnf
+import functest.utils.openstack_utils as os_utils
+from functest.utils.constants import CONST
+
+from org.openbaton.cli.errors.errors import NfvoException
+from org.openbaton.cli.agents.agents import MainAgent
+
+
+__author__ = "Pauls, Michael <michael.pauls@fokus.fraunhofer.de>"
+# ----------------------------------------------------------
+#
+# UTILS
+#
+# -----------------------------------------------------------
+
+
+def get_config(parameter, file_path):
+ """
+ Get config parameter.
+
+ Returns the value of a given parameter in file.yaml
+ parameter must be given in string format with dots
+ Example: general.openstack.image_name
+ """
+ with open(file_path) as config_file:
+ file_yaml = yaml.safe_load(config_file)
+ config_file.close()
+ value = file_yaml
+ for element in parameter.split("."):
+ value = value.get(element)
+ if value is None:
+ raise ValueError("The parameter %s is not defined in"
+ " reporting.yaml", parameter)
+ return value
+
+
+def servertest(host, port):
+ """Method to test that a server is reachable at IP:port"""
+ args = socket.getaddrinfo(host, port, socket.AF_INET, socket.SOCK_STREAM)
+ for family, socktype, proto, canonname, sockaddr in args:
+ sock = socket.socket(family, socktype, proto)
+ try:
+ sock.connect(sockaddr)
+ except socket.error:
+ return False
+ else:
+ sock.close()
+ return True
+
+
+def get_userdata(orchestrator=dict):
+ """Build userdata for Open Baton machine"""
+ userdata = "#!/bin/bash\n"
+ userdata += "echo \"Executing userdata...\"\n"
+ userdata += "set -x\n"
+ userdata += "set -e\n"
+ userdata += "echo \"Set nameserver to '8.8.8.8'...\"\n"
+ userdata += "echo \"nameserver 8.8.8.8\" >> /etc/resolv.conf\n"
+ userdata += "echo \"Install curl...\"\n"
+ userdata += "apt-get install curl\n"
+ userdata += "echo \"Inject public key...\"\n"
+ userdata += ("echo \"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCuPXrV3"
+ "geeHc6QUdyUr/1Z+yQiqLcOskiEGBiXr4z76MK4abiFmDZ18OMQlc"
+ "fl0p3kS0WynVgyaOHwZkgy/DIoIplONVr2CKBKHtPK+Qcme2PVnCtv"
+ "EqItl/FcD+1h5XSQGoa+A1TSGgCod/DPo+pes0piLVXP8Ph6QS1k7S"
+ "ic7JDeRQ4oT1bXYpJ2eWBDMfxIWKZqcZRiGPgMIbJ1iEkxbpeaAd9O"
+ "4MiM9nGCPESmed+p54uYFjwEDlAJZShcAZziiZYAvMZhvAhe6USljc"
+ "7YAdalAnyD/jwCHuwIrUw/lxo7UdNCmaUxeobEYyyFA1YVXzpNFZya"
+ "XPGAAYIJwEq/ openbaton@opnfv\" >> /home/ubuntu/.ssh/aut"
+ "horized_keys\n")
+ userdata += "echo \"Download bootstrap...\"\n"
+ userdata += ("curl -s %s "
+ "> ./bootstrap\n" % orchestrator['bootstrap']['url'])
+ userdata += ("curl -s %s" "> ./config_file\n" %
+ orchestrator['bootstrap']['config']['url'])
+ userdata += ("echo \"Disable usage of mysql...\"\n")
+ userdata += "sed -i s/mysql=.*/mysql=no/g /config_file\n"
+ userdata += ("echo \"Setting 'rabbitmq_broker_ip' to '%s'\"\n"
+ % orchestrator['details']['fip'].ip)
+ userdata += ("sed -i s/rabbitmq_broker_ip=localhost/rabbitmq_broker_ip"
+ "=%s/g /config_file\n" % orchestrator['details']['fip'].ip)
+ userdata += "echo \"Set autostart of components to 'false'\"\n"
+ userdata += "export OPENBATON_COMPONENT_AUTOSTART=false\n"
+ userdata += "echo \"Execute bootstrap...\"\n"
+ bootstrap = "sh ./bootstrap release -configFile=./config_file"
+ userdata += bootstrap + "\n"
+ userdata += "echo \"Setting 'nfvo.plugin.timeout' to '300000'\"\n"
+ userdata += ("echo \"nfvo.plugin.timeout=600000\" >> "
+ "/etc/openbaton/openbaton-nfvo.properties\n")
+ userdata += (
+ "wget %s -O /etc/openbaton/openbaton-vnfm-generic-user-data.sh\n" %
+ orchestrator['gvnfm']['userdata']['url'])
+ userdata += "sed -i '113i"'\ \ \ \ '"sleep 60' " \
+ "/etc/openbaton/openbaton-vnfm-generic-user-data.sh\n"
+ userdata += "echo \"Starting NFVO\"\n"
+ userdata += "service openbaton-nfvo restart\n"
+ userdata += "echo \"Starting Generic VNFM\"\n"
+ userdata += "service openbaton-vnfm-generic restart\n"
+ userdata += "echo \"...end of userdata...\"\n"
+ return userdata
+
+
+class ClearwaterImsVnf(vnf.VnfOnBoarding):
+ """Clearwater IMS VNF deployed with openBaton orchestrator"""
+
+ logger = logging.getLogger(__name__)
+
+ def __init__(self, **kwargs):
+ if "case_name" not in kwargs:
+ kwargs["case_name"] = "orchestra_clearwaterims"
+ super(ClearwaterImsVnf, self).__init__(**kwargs)
+ # self.logger = logging.getLogger("functest.ci.run_tests.orchestra")
+ self.logger.info("kwargs %s", (kwargs))
+
+ self.case_dir = pkg_resources.resource_filename(
+ 'functest', 'opnfv_tests/vnf/ims/')
+ self.data_dir = CONST.__getattribute__('dir_ims_data')
+ self.test_dir = CONST.__getattribute__('dir_repo_vims_test')
+ self.created_resources = []
+ self.logger.info("%s VNF onboarding test starting", self.case_name)
+
+ try:
+ self.config = CONST.__getattribute__(
+ 'vnf_{}_config'.format(self.case_name))
+ except BaseException:
+ raise Exception("Orchestra VNF config file not found")
+ config_file = self.case_dir + self.config
+
+ self.mano = dict(
+ get_config("mano", config_file),
+ details={}
+ )
+ self.logger.debug("Orchestrator configuration %s", self.mano)
+
+ self.details['orchestrator'] = dict(
+ name=self.mano['name'],
+ version=self.mano['version'],
+ status='ERROR',
+ result=''
+ )
+
+ self.vnf = dict(
+ get_config(self.case_name, config_file),
+ )
+ self.logger.debug("VNF configuration: %s", self.vnf)
+
+ self.details['vnf'] = dict(
+ name=self.vnf['name'],
+ )
+
+ self.details['test_vnf'] = dict(
+ name=self.case_name,
+ )
+
+ # Orchestra base Data directory creation
+ if not os.path.exists(self.data_dir):
+ os.makedirs(self.data_dir)
+
+ self.images = get_config("tenant_images.orchestrator", config_file)
+ self.images.update(
+ get_config(
+ "tenant_images.%s" %
+ self.case_name,
+ config_file))
+ self.snaps_creds = None
+
+ def prepare(self):
+ """Prepare testscase (Additional pre-configuration steps)."""
+ super(ClearwaterImsVnf, self).prepare()
+
+ self.logger.info("Additional pre-configuration steps")
+ self.logger.info("creds %s", (self.creds))
+
+ self.snaps_creds = OSCreds(
+ username=self.creds['username'],
+ password=self.creds['password'],
+ auth_url=self.creds['auth_url'],
+ project_name=self.creds['tenant'],
+ identity_api_version=int(os_utils.get_keystone_client_version()))
+
+ self.prepare_images()
+ self.prepare_flavor()
+ self.prepare_security_groups()
+ self.prepare_network()
+ self.prepare_floating_ip()
+
+ def prepare_images(self):
+ """Upload images if they doen't exist yet"""
+ self.logger.info("Upload images if they doen't exist yet")
+ for image_name, image_file in self.images.iteritems():
+ self.logger.info("image: %s, file: %s", image_name, image_file)
+ if image_file and image_name:
+ image = OpenStackImage(
+ self.snaps_creds,
+ ImageSettings(name=image_name,
+ image_user='cloud',
+ img_format='qcow2',
+ image_file=image_file))
+ image.create()
+ # self.created_resources.append(image);
+
+ def prepare_security_groups(self):
+ """Create Open Baton security group if it doesn't exist yet"""
+ self.logger.info(
+ "Creating security group for Open Baton if not yet existing...")
+ sg_rules = list()
+ sg_rules.append(
+ SecurityGroupRuleSettings(
+ sec_grp_name="orchestra-sec-group-allowall",
+ direction=Direction.ingress,
+ protocol=Protocol.tcp,
+ port_range_min=1,
+ port_range_max=65535))
+ sg_rules.append(
+ SecurityGroupRuleSettings(
+ sec_grp_name="orchestra-sec-group-allowall",
+ direction=Direction.egress,
+ protocol=Protocol.tcp,
+ port_range_min=1,
+ port_range_max=65535))
+ sg_rules.append(
+ SecurityGroupRuleSettings(
+ sec_grp_name="orchestra-sec-group-allowall",
+ direction=Direction.ingress,
+ protocol=Protocol.udp,
+ port_range_min=1,
+ port_range_max=65535))
+ sg_rules.append(
+ SecurityGroupRuleSettings(
+ sec_grp_name="orchestra-sec-group-allowall",
+ direction=Direction.egress,
+ protocol=Protocol.udp,
+ port_range_min=1,
+ port_range_max=65535))
+ sg_rules.append(
+ SecurityGroupRuleSettings(
+ sec_grp_name="orchestra-sec-group-allowall",
+ direction=Direction.ingress,
+ protocol=Protocol.icmp))
+ sg_rules.append(
+ SecurityGroupRuleSettings(
+ sec_grp_name="orchestra-sec-group-allowall",
+ direction=Direction.egress,
+ protocol=Protocol.icmp))
+ # sg_rules.append(
+ # SecurityGroupRuleSettings(
+ # sec_grp_name="orchestra-sec-group-allowall",
+ # direction=Direction.ingress,
+ # protocol=Protocol.icmp,
+ # port_range_min=-1,
+ # port_range_max=-1))
+ # sg_rules.append(
+ # SecurityGroupRuleSettings(
+ # sec_grp_name="orchestra-sec-group-allowall",
+ # direction=Direction.egress,
+ # protocol=Protocol.icmp,
+ # port_range_min=-1,
+ # port_range_max=-1))
+
+ security_group = OpenStackSecurityGroup(
+ self.snaps_creds,
+ SecurityGroupSettings(
+ name="orchestra-sec-group-allowall",
+ rule_settings=sg_rules))
+
+ security_group_info = security_group.create()
+ self.created_resources.append(security_group)
+ self.mano['details']['sec_group'] = security_group_info.name
+ self.logger.info(
+ "Security group orchestra-sec-group-allowall prepared")
+
+ def prepare_flavor(self):
+ """Create Open Baton flavor if it doesn't exist yet"""
+ self.logger.info(
+ "Create Flavor for Open Baton NFVO if not yet existing")
+
+ flavor_settings = FlavorSettings(
+ name=self.mano['requirements']['flavor']['name'],
+ ram=self.mano['requirements']['flavor']['ram_min'],
+ disk=self.mano['requirements']['flavor']['disk'],
+ vcpus=self.mano['requirements']['flavor']['vcpus'])
+ flavor = OpenStackFlavor(self.snaps_creds, flavor_settings)
+ flavor_info = flavor.create()
+ self.created_resources.append(flavor)
+ self.mano['details']['flavor'] = {}
+ self.mano['details']['flavor']['name'] = flavor_settings.name
+ self.mano['details']['flavor']['id'] = flavor_info.id
+
+ def prepare_network(self):
+ """Create network/subnet/router if they doen't exist yet"""
+ self.logger.info(
+ "Creating network/subnet/router if they doen't exist yet...")
+ subnet_settings = SubnetSettings(
+ name='%s_subnet' %
+ self.case_name,
+ cidr="192.168.100.0/24")
+ network_settings = NetworkSettings(
+ name='%s_net' %
+ self.case_name,
+ subnet_settings=[subnet_settings])
+ orchestra_network = OpenStackNetwork(
+ self.snaps_creds, network_settings)
+ orchestra_network_info = orchestra_network.create()
+ self.mano['details']['network'] = {}
+ self.mano['details']['network']['id'] = orchestra_network_info.id
+ self.mano['details']['network']['name'] = orchestra_network_info.name
+ self.mano['details']['external_net_name'] = snaps_utils.\
+ get_ext_net_name(self.snaps_creds)
+ self.created_resources.append(orchestra_network)
+ orchestra_router = OpenStackRouter(
+ self.snaps_creds,
+ RouterSettings(
+ name='%s_router' %
+ self.case_name,
+ external_gateway=self.mano['details']['external_net_name'],
+ internal_subnets=[
+ subnet_settings.name]))
+ orchestra_router.create()
+ self.created_resources.append(orchestra_router)
+ self.logger.info("Created network and router for Open Baton NFVO...")
+
+ def prepare_floating_ip(self):
+ """Select/Create Floating IP if it doesn't exist yet"""
+ self.logger.info("Retrieving floating IP for Open Baton NFVO")
+ neutron_client = snaps_utils.neutron_utils.neutron_client(
+ self.snaps_creds)
+ # Finding Tenant ID to check to which tenant the Floating IP belongs
+ tenant_id = os_utils.get_tenant_id(
+ os_utils.get_keystone_client(self.creds),
+ self.tenant_name)
+ # Use os_utils to retrieve complete information of Floating IPs
+ floating_ips = os_utils.get_floating_ips(neutron_client)
+ my_floating_ips = []
+ # Filter Floating IPs with tenant id
+ for floating_ip in floating_ips:
+ # self.logger.info("Floating IP: %s", floating_ip)
+ if floating_ip.get('tenant_id') == tenant_id:
+ my_floating_ips.append(floating_ip.get('floating_ip_address'))
+ # Select if Floating IP exist else create new one
+ if len(my_floating_ips) >= 1:
+ # Get Floating IP object from snaps for clean up
+ snaps_floating_ips = snaps_utils.neutron_utils.get_floating_ips(
+ neutron_client)
+ for my_floating_ip in my_floating_ips:
+ for snaps_floating_ip in snaps_floating_ips:
+ if snaps_floating_ip.ip == my_floating_ip:
+ self.mano['details']['fip'] = snaps_floating_ip
+ self.logger.info(
+ "Selected floating IP for Open Baton NFVO %s",
+ (self.mano['details']['fip'].ip))
+ break
+ if self.mano['details']['fip'] is not None:
+ break
+ else:
+ self.logger.info("Creating floating IP for Open Baton NFVO")
+ self.mano['details']['fip'] = snaps_utils.neutron_utils.\
+ create_floating_ip(
+ neutron_client,
+ self.mano['details']['external_net_name'])
+ self.logger.info(
+ "Created floating IP for Open Baton NFVO %s",
+ (self.mano['details']['fip'].ip))
+
+ def get_vim_descriptor(self):
+ """"Create VIM descriptor to be used for onboarding"""
+ self.logger.info(
+ "Building VIM descriptor with PoP creds: %s",
+ self.creds)
+ # Depending on API version either tenant ID or project name must be
+ # used
+ if os_utils.is_keystone_v3():
+ self.logger.info(
+ "Using v3 API of OpenStack... -> Using OS_PROJECT_ID")
+ project_id = os_utils.get_tenant_id(
+ os_utils.get_keystone_client(),
+ self.creds.get("project_name"))
+ else:
+ self.logger.info(
+ "Using v2 API of OpenStack... -> Using OS_TENANT_NAME")
+ project_id = self.creds.get("tenant_name")
+ self.logger.debug("VIM project/tenant id: %s", project_id)
+ vim_json = {
+ "name": "vim-instance",
+ "authUrl": self.creds.get("auth_url"),
+ "tenant": project_id,
+ "username": self.creds.get("username"),
+ "password": self.creds.get("password"),
+ "securityGroups": [
+ self.mano['details']['sec_group']
+ ],
+ "type": "openstack",
+ "location": {
+ "name": "opnfv",
+ "latitude": "52.525876",
+ "longitude": "13.314400"
+ }
+ }
+ self.logger.info("Built VIM descriptor: %s", vim_json)
+ return vim_json
+
+ def deploy_orchestrator(self):
+ self.logger.info("Deploying Open Baton...")
+ self.logger.info("Details: %s", self.mano['details'])
+ start_time = time.time()
+
+ self.logger.info("Creating orchestra instance...")
+ userdata = get_userdata(self.mano)
+ self.logger.info("flavor: %s\n"
+ "image: %s\n"
+ "network_id: %s\n",
+ self.mano['details']['flavor']['name'],
+ self.mano['requirements']['image'],
+ self.mano['details']['network']['id'])
+ self.logger.debug("userdata: %s\n", userdata)
+ # setting up image
+ image_settings = ImageSettings(
+ name=self.mano['requirements']['image'],
+ image_user='ubuntu',
+ exists=True)
+ # setting up port
+ port_settings = PortSettings(
+ name='%s_port' % self.case_name,
+ network_name=self.mano['details']['network']['name'])
+ # build configuration of vm
+ orchestra_settings = VmInstanceSettings(
+ name=self.case_name,
+ flavor=self.mano['details']['flavor']['name'],
+ port_settings=[port_settings],
+ security_group_names=[self.mano['details']['sec_group']],
+ userdata=userdata)
+ orchestra_vm = OpenStackVmInstance(self.snaps_creds,
+ orchestra_settings,
+ image_settings)
+
+ orchestra_vm.create()
+ self.created_resources.append(orchestra_vm)
+ self.mano['details']['id'] = orchestra_vm.get_vm_info()['id']
+ self.logger.info(
+ "Created orchestra instance: %s",
+ self.mano['details']['id'])
+
+ self.logger.info("Associating floating ip: '%s' to VM '%s' ",
+ self.mano['details']['fip'].ip,
+ self.case_name)
+ nova_client = os_utils.get_nova_client()
+ if not os_utils.add_floating_ip(
+ nova_client,
+ self.mano['details']['id'],
+ self.mano['details']['fip'].ip):
+ duration = time.time() - start_time
+ self.details["orchestrator"].update(
+ status='FAIL', duration=duration)
+ self.logger.error("Cannot associate floating IP to VM.")
+ return False
+
+ self.logger.info("Waiting for Open Baton NFVO to be up and running...")
+ timeout = 0
+ while timeout < 200:
+ if servertest(
+ self.mano['details']['fip'].ip,
+ "8080"):
+ break
+ else:
+ self.logger.info(
+ "Open Baton NFVO is not started yet (%ss)",
+ (timeout * 5))
+ time.sleep(5)
+ timeout += 1
+
+ if timeout >= 200:
+ duration = time.time() - start_time
+ self.details["orchestrator"].update(
+ status='FAIL', duration=duration)
+ self.logger.error("Open Baton is not started correctly")
+ return False
+
+ self.logger.info("Waiting for all components to be up and running...")
+ time.sleep(60)
+ duration = time.time() - start_time
+ self.details["orchestrator"].update(status='PASS', duration=duration)
+ self.logger.info("Deploy Open Baton NFVO: OK")
+ return True
+
+ def deploy_vnf(self):
+ start_time = time.time()
+ self.logger.info("Deploying %s...", self.vnf['name'])
+
+ main_agent = MainAgent(
+ nfvo_ip=self.mano['details']['fip'].ip,
+ nfvo_port=8080,
+ https=False,
+ version=1,
+ username=self.mano['credentials']['username'],
+ password=self.mano['credentials']['password'])
+
+ self.logger.info(
+ "Create %s Flavor if not existing", self.vnf['name'])
+ flavor_settings = FlavorSettings(
+ name=self.vnf['requirements']['flavor']['name'],
+ ram=self.vnf['requirements']['flavor']['ram_min'],
+ disk=self.vnf['requirements']['flavor']['disk'],
+ vcpus=self.vnf['requirements']['flavor']['vcpus'])
+ flavor = OpenStackFlavor(self.snaps_creds, flavor_settings)
+ flavor_info = flavor.create()
+ self.logger.debug("Flavor id: %s", flavor_info.id)
+
+ self.logger.info("Getting project 'default'...")
+ project_agent = main_agent.get_agent("project", "")
+ for project in json.loads(project_agent.find()):
+ if project.get("name") == "default":
+ self.mano['details']['project_id'] = project.get("id")
+ self.logger.info("Found project 'default': %s", project)
+ break
+
+ vim_json = self.get_vim_descriptor()
+ self.logger.info("Registering VIM: %s", vim_json)
+
+ main_agent.get_agent(
+ "vim", project_id=self.mano['details']['project_id']).create(
+ entity=json.dumps(vim_json))
+
+ market_agent = main_agent.get_agent(
+ "market", project_id=self.mano['details']['project_id'])
+
+ try:
+ self.logger.info("sending: %s", self.vnf['descriptor']['url'])
+ nsd = market_agent.create(entity=self.vnf['descriptor']['url'])
+ if nsd.get('id') is None:
+ self.logger.error("NSD not onboarded correctly")
+ duration = time.time() - start_time
+ self.details["vnf"].update(status='FAIL', duration=duration)
+ return False
+ self.mano['details']['nsd_id'] = nsd.get('id')
+ self.logger.info("Onboarded NSD: " + nsd.get("name"))
+
+ nsr_agent = main_agent.get_agent(
+ "nsr", project_id=self.mano['details']['project_id'])
+
+ self.mano['details']['nsr'] = nsr_agent.create(
+ self.mano['details']['nsd_id'])
+ except NfvoException as exc:
+ self.logger.error(exc.message)
+ duration = time.time() - start_time
+ self.details["vnf"].update(status='FAIL', duration=duration)
+ return False
+
+ if self.mano['details']['nsr'].get('code') is not None:
+ self.logger.error(
+ "%s cannot be deployed: %s -> %s",
+ self.vnf['name'],
+ self.mano['details']['nsr'].get('code'),
+ self.mano['details']['nsr'].get('message'))
+ self.logger.error("%s cannot be deployed", self.vnf['name'])
+ duration = time.time() - start_time
+ self.details["vnf"].update(status='FAIL', duration=duration)
+ return False
+
+ timeout = 0
+ self.logger.info("Waiting for NSR to go to ACTIVE...")
+ while self.mano['details']['nsr'].get("status") != 'ACTIVE' \
+ and self.mano['details']['nsr'].get("status") != 'ERROR':
+ timeout += 1
+ self.logger.info("NSR is not yet ACTIVE... (%ss)", 5 * timeout)
+ if timeout == 300:
+ self.logger.error("INACTIVE NSR after %s sec..", 5 * timeout)
+ duration = time.time() - start_time
+ self.details["vnf"].update(status='FAIL', duration=duration)
+ return False
+ time.sleep(5)
+ self.mano['details']['nsr'] = json.loads(
+ nsr_agent.find(self.mano['details']['nsr'].get('id')))
+
+ duration = time.time() - start_time
+ if self.mano['details']['nsr'].get("status") == 'ACTIVE':
+ self.details["vnf"].update(status='PASS', duration=duration)
+ self.logger.info("Sleep for 60s to ensure that all "
+ "services are up and running...")
+ time.sleep(60)
+ result = True
+ else:
+ self.details["vnf"].update(status='FAIL', duration=duration)
+ self.logger.error("NSR: %s", self.mano['details'].get('nsr'))
+ result = False
+ return result
+
+ def test_vnf(self):
+ self.logger.info(
+ "Testing VNF Clearwater IMS is not yet implemented...")
+ start_time = time.time()
+
+ duration = time.time() - start_time
+ self.details["test_vnf"].update(status='PASS', duration=duration)
+ self.logger.info("Test VNF: OK")
+ return True
+
+ def clean(self):
+ self.logger.info("Cleaning %s...", self.case_name)
+ try:
+ main_agent = MainAgent(
+ nfvo_ip=self.mano['details']['fip'].ip,
+ nfvo_port=8080,
+ https=False,
+ version=1,
+ username=self.mano['credentials']['username'],
+ password=self.mano['credentials']['password'])
+ self.logger.info("Terminating %s...", self.vnf['name'])
+ if (self.mano['details'].get('nsr')):
+ main_agent.get_agent(
+ "nsr",
+ project_id=self.mano['details']['project_id']).delete(
+ self.mano['details']['nsr'].get('id'))
+ self.logger.info("Sleeping 60 seconds...")
+ time.sleep(60)
+ else:
+ self.logger.info("No need to terminate the VNF...")
+ # os_utils.delete_instance(nova_client=os_utils.get_nova_client(),
+ # instance_id=self.mano_instance_id)
+ except (NfvoException, KeyError) as exc:
+ self.logger.error('Unexpected error cleaning - %s', exc)
+
+ try:
+ neutron_client = os_utils.get_neutron_client(self.creds)
+ self.logger.info("Deleting Open Baton Port...")
+ port = snaps_utils.neutron_utils.get_port_by_name(
+ neutron_client, '%s_port' % self.case_name)
+ snaps_utils.neutron_utils.delete_port(neutron_client, port)
+ time.sleep(10)
+ except Exception as exc:
+ self.logger.error('Unexpected error cleaning - %s', exc)
+ try:
+ self.logger.info("Deleting Open Baton Floating IP...")
+ snaps_utils.neutron_utils.delete_floating_ip(
+ neutron_client, self.mano['details']['fip'])
+ except Exception as exc:
+ self.logger.error('Unexpected error cleaning - %s', exc)
+
+ for resource in reversed(self.created_resources):
+ try:
+ self.logger.info("Cleaning %s", str(resource))
+ resource.clean()
+ except Exception as exc:
+ self.logger.error('Unexpected error cleaning - %s', exc)
+ super(ClearwaterImsVnf, self).clean()
diff --git a/functest/opnfv_tests/vnf/ims/orchestra_ims.py b/functest/opnfv_tests/vnf/ims/orchestra_ims.py
deleted file mode 100644
index 7b1ea9ad..00000000
--- a/functest/opnfv_tests/vnf/ims/orchestra_ims.py
+++ /dev/null
@@ -1,487 +0,0 @@
-#!/usr/bin/env python
-
-# Copyright (c) 2016 Orange and others.
-#
-# All rights reserved. This program and the accompanying materials
-# are made available under the terms of the Apache License, Version 2.0
-# which accompanies this distribution, and is available at
-# http://www.apache.org/licenses/LICENSE-2.0
-
-import json
-import logging
-import os
-import pkg_resources
-import socket
-import sys
-import time
-import yaml
-
-import functest.core.vnf as vnf
-import functest.utils.openstack_utils as os_utils
-from functest.utils.constants import CONST
-
-from org.openbaton.cli.agents.agents import MainAgent
-from org.openbaton.cli.errors.errors import NfvoException
-
-
-__author__ = "Pauls, Michael <michael.pauls@fokus.fraunhofer.de>"
-# ----------------------------------------------------------
-#
-# UTILS
-#
-# -----------------------------------------------------------
-
-
-def get_config(parameter, my_file):
- """
- Returns the value of a given parameter in file.yaml
- parameter must be given in string format with dots
- Example: general.openstack.image_name
- """
- with open(file) as f:
- file_yaml = yaml.safe_load(f)
- f.close()
- value = file_yaml
- for element in parameter.split("."):
- value = value.get(element)
- if value is None:
- raise ValueError("The parameter %s is not defined in"
- " %s" % (parameter, my_file))
- return value
-
-
-def servertest(host, port):
- args = socket.getaddrinfo(host, port, socket.AF_INET, socket.SOCK_STREAM)
- for family, socktype, proto, canonname, sockaddr in args:
- s = socket.socket(family, socktype, proto)
- try:
- s.connect(sockaddr)
- except socket.error:
- return False
- else:
- s.close()
- return True
-
-
-class ImsVnf(vnf.VnfOnBoarding):
- """OpenIMS VNF deployed with openBaton orchestrator"""
-
- def __init__(self, project='functest', case_name='orchestra_ims',
- repo='', cmd=''):
- super(ImsVnf, self).__init__(project, case_name, repo, cmd)
- self.logger = logging.getLogger(__name__)
- self.logger.info("Orchestra IMS VNF onboarding test starting")
- self.ob_password = "openbaton"
- self.ob_username = "admin"
- self.ob_https = False
- self.ob_port = "8080"
- self.ob_ip = "localhost"
- self.ob_instance_id = ""
- self.case_dir = pkg_resources.resource_filename(
- 'functest', 'opnfv_tests/vnf/ims/')
- self.data_dir = CONST.__getattribute__('dir_ims_data')
- self.test_dir = CONST.__getattribute__('dir_repo_vims_test')
- self.ob_projectid = ""
- self.keystone_client = os_utils.get_keystone_client()
- self.ob_nsr_id = ""
- self.nsr = None
- self.main_agent = None
- # vIMS Data directory creation
- if not os.path.exists(self.data_dir):
- os.makedirs(self.data_dir)
- # Retrieve the configuration
- try:
- self.config = CONST.__getattribute__(
- 'vnf_{}_config'.format(self.case_name))
- except BaseException:
- raise Exception("Orchestra VNF config file not found")
- config_file = self.case_dir + self.config
- self.imagename = get_config("openbaton.imagename", config_file)
- self.bootstrap_link = get_config("openbaton.bootstrap_link",
- config_file)
- self.bootstrap_config_link = get_config(
- "openbaton.bootstrap_config_link", config_file)
- self.market_link = get_config("openbaton.marketplace_link",
- config_file)
- self.images = get_config("tenant_images", config_file)
- self.ims_conf = get_config("vIMS", config_file)
- self.userdata_file = get_config("openbaton.userdata.file",
- config_file)
-
- def deploy_orchestrator(self):
- self.logger.info("Additional pre-configuration steps")
- nova_client = os_utils.get_nova_client()
- neutron_client = os_utils.get_neutron_client()
- glance_client = os_utils.get_glance_client()
-
- # Import images if needed
- # needs some images
- self.logger.info("Upload some OS images if it doesn't exist")
- temp_dir = os.path.join(self.data_dir, "tmp/")
- for image_name, image_url in self.images.iteritems():
- self.logger.info("image: %s, url: %s", image_name, image_url)
- try:
- image_id = os_utils.get_image_id(glance_client,
- image_name)
- self.logger.info("image_id: %s", image_id)
- except BaseException:
- self.logger.error("Unexpected error: %s", sys.exc_info()[0])
-
- if image_id == '':
- self.logger.info("""%s image doesn't exist on glance
- repository. Try downloading this image
- and upload on glance !""" % image_name)
- image_id = os_utils.download_and_add_image_on_glance(
- glance_client,
- image_name,
- image_url,
- temp_dir)
- if image_id == '':
- self.logger.error("Failed to find or upload required OS "
- "image for this deployment")
- return False
-
- network_dic = os_utils.create_network_full(neutron_client,
- "openbaton_mgmt",
- "openbaton_mgmt_subnet",
- "openbaton_router",
- "192.168.100.0/24")
-
- # orchestrator VM flavor
- self.logger.info(
- "Check if orchestra Flavor is available, if not create one")
- flavor_exist, flavor_id = os_utils.get_or_create_flavor(
- "orchestra",
- "4096",
- '20',
- '2',
- public=True)
- self.logger.debug("Flavor id: %s" % flavor_id)
-
- if not network_dic:
- self.logger.error("There has been a problem when creating the "
- "neutron network")
-
- network_id = network_dic["net_id"]
-
- self.logger.info("Creating floating IP for VM in advance...")
- floatip_dic = os_utils.create_floating_ip(neutron_client)
- floatip = floatip_dic['fip_addr']
-
- if floatip is None:
- self.logger.error("Cannot create floating IP.")
- return False
-
- userdata = "#!/bin/bash\n"
- userdata += "echo \"Executing userdata...\"\n"
- userdata += "set -x\n"
- userdata += "set -e\n"
- userdata += "echo \"Set nameserver to '8.8.8.8'...\"\n"
- userdata += "echo \"nameserver 8.8.8.8\" >> /etc/resolv.conf\n"
- userdata += "echo \"Install curl...\"\n"
- userdata += "apt-get install curl\n"
- userdata += "echo \"Inject public key...\"\n"
- userdata += ("echo \"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCuPXrV3"
- "geeHc6QUdyUr/1Z+yQiqLcOskiEGBiXr4z76MK4abiFmDZ18OMQlc"
- "fl0p3kS0WynVgyaOHwZkgy/DIoIplONVr2CKBKHtPK+Qcme2PVnCtv"
- "EqItl/FcD+1h5XSQGoa+A1TSGgCod/DPo+pes0piLVXP8Ph6QS1k7S"
- "ic7JDeRQ4oT1bXYpJ2eWBDMfxIWKZqcZRiGPgMIbJ1iEkxbpeaAd9O"
- "4MiM9nGCPESmed+p54uYFjwEDlAJZShcAZziiZYAvMZhvAhe6USljc"
- "7YAdalAnyD/jwCHuwIrUw/lxo7UdNCmaUxeobEYyyFA1YVXzpNFZya"
- "XPGAAYIJwEq/ openbaton@opnfv\" >> /home/ubuntu/.ssh/aut"
- "horized_keys\n")
- userdata += "echo \"Download bootstrap...\"\n"
- userdata += ("curl -s %s "
- "> ./bootstrap\n" % self.bootstrap_link)
- userdata += ("curl -s %s"
- "> ./config_file\n" % self.bootstrap_config_link)
- userdata += ("echo \"Disable usage of mysql...\"\n")
- userdata += "sed -i s/mysql=.*/mysql=no/g /config_file\n"
- userdata += ("echo \"Setting 'rabbitmq_broker_ip' to '%s'\"\n"
- % floatip)
- userdata += ("sed -i s/rabbitmq_broker_ip=localhost/rabbitmq_broker_ip"
- "=%s/g /config_file\n" % floatip)
- userdata += "echo \"Set autostart of components to 'false'\"\n"
- userdata += "export OPENBATON_COMPONENT_AUTOSTART=false\n"
- userdata += "echo \"Execute bootstrap...\"\n"
- bootstrap = "sh ./bootstrap release -configFile=./config_file"
- userdata += bootstrap + "\n"
- userdata += "echo \"Setting 'nfvo.plugin.timeout' to '300000'\"\n"
- userdata += ("echo \"nfvo.plugin.timeout=600000\" >> "
- "/etc/openbaton/openbaton-nfvo.properties\n")
- userdata += (
- "wget %s -O /etc/openbaton/openbaton-vnfm-generic-user-data.sh\n" %
- self.userdata_file)
- userdata += "sed -i '113i\ \ \ \ sleep 60' " \
- "/etc/openbaton/openbaton-vnfm-generic-user-data.sh\n"
- userdata += "echo \"Starting NFVO\"\n"
- userdata += "service openbaton-nfvo restart\n"
- userdata += "echo \"Starting Generic VNFM\"\n"
- userdata += "service openbaton-vnfm-generic restart\n"
- userdata += "echo \"...end of userdata...\"\n"
-
- sg_id = os_utils.create_security_group_full(neutron_client,
- "orchestra-sec-group",
- "allowall")
-
- os_utils.create_secgroup_rule(neutron_client, sg_id, "ingress",
- "icmp", 0, 255)
- os_utils.create_secgroup_rule(neutron_client, sg_id, "egress",
- "icmp", 0, 255)
- os_utils.create_secgroup_rule(neutron_client, sg_id, "ingress",
- "tcp", 1, 65535)
- os_utils.create_secgroup_rule(neutron_client, sg_id, "ingress",
- "udp", 1, 65535)
- os_utils.create_secgroup_rule(neutron_client, sg_id, "egress",
- "tcp", 1, 65535)
- os_utils.create_secgroup_rule(neutron_client, sg_id, "egress",
- "udp", 1, 65535)
-
- self.logger.info("Security group set")
-
- self.logger.info("Create instance....")
- self.logger.info("flavor: m1.medium\n"
- "image: %s\n"
- "network_id: %s\n"
- "userdata: %s\n",
- self.imagename,
- network_id,
- userdata)
-
- instance = os_utils.create_instance_and_wait_for_active(
- "orchestra",
- os_utils.get_image_id(glance_client, self.imagename),
- network_id,
- "orchestra-openbaton",
- config_drive=False,
- userdata=userdata)
-
- self.ob_instance_id = instance.id
-
- self.logger.info("Adding sec group to orchestra instance")
- os_utils.add_secgroup_to_instance(nova_client,
- self.ob_instance_id, sg_id)
-
- self.logger.info("Associating floating ip: '%s' to VM '%s' ",
- floatip,
- "orchestra-openbaton")
- if not os_utils.add_floating_ip(nova_client, instance.id, floatip):
- self.logger.error("Cannot associate floating IP to VM.")
- return False
-
- self.logger.info("Waiting for Open Baton NFVO to be up and running...")
- x = 0
- while x < 200:
- if servertest(floatip, "8080"):
- break
- else:
- self.logger.debug(
- "Open Baton NFVO is not started yet (%ss)" %
- (x * 5))
- time.sleep(5)
- x += 1
-
- if x == 200:
- self.logger.error("Open Baton is not started correctly")
-
- self.ob_ip = floatip
- self.ob_password = "openbaton"
- self.ob_username = "admin"
- self.ob_https = False
- self.ob_port = "8080"
- self.logger.info("Waiting for all components up and running...")
- time.sleep(60)
- self.details["orchestrator"] = {
- 'status': "PASS", 'result': "Deploy Open Baton NFVO: OK"}
- self.logger.info("Deploy Open Baton NFVO: OK")
- return True
-
- def deploy_vnf(self):
- self.logger.info("Starting vIMS Deployment...")
-
- self.main_agent = MainAgent(nfvo_ip=self.ob_ip,
- nfvo_port=self.ob_port,
- https=self.ob_https,
- version=1,
- username=self.ob_username,
- password=self.ob_password)
-
- self.logger.info(
- "Check if openims Flavor is available, if not create one")
- flavor_exist, flavor_id = os_utils.get_or_create_flavor(
- "m1.small",
- "2048",
- '20',
- '1',
- public=True)
- self.logger.debug("Flavor id: %s", flavor_id)
-
- self.logger.info("Getting project 'default'...")
- project_agent = self.main_agent.get_agent("project", self.ob_projectid)
- for p in json.loads(project_agent.find()):
- if p.get("name") == "default":
- self.ob_projectid = p.get("id")
- self.logger.info("Found project 'default': %s", p)
- break
-
- self.logger.debug("project id: %s", self.ob_projectid)
- if self.ob_projectid == "":
- self.logger.error("Default project id was not found!")
-
- creds = os_utils.get_credentials()
- self.logger.info("PoP creds: %s", creds)
-
- if os_utils.is_keystone_v3():
- self.logger.info(
- "Using v3 API of OpenStack... -> Using OS_PROJECT_ID")
- project_id = os_utils.get_tenant_id(
- os_utils.get_keystone_client(),
- creds.get("project_name"))
- else:
- self.logger.info(
- "Using v2 API of OpenStack... -> Using OS_TENANT_NAME")
- project_id = creds.get("tenant_name")
-
- self.logger.debug("project id: %s", project_id)
-
- vim_json = {
- "name": "vim-instance",
- "authUrl": creds.get("auth_url"),
- "tenant": project_id,
- "username": creds.get("username"),
- "password": creds.get("password"),
- "securityGroups": [
- "default",
- "orchestra-sec-group"
- ],
- "type": "openstack",
- "location": {
- "name": "opnfv",
- "latitude": "52.525876",
- "longitude": "13.314400"
- }
- }
-
- self.logger.debug("Registering VIM: %s", vim_json)
-
- self.main_agent.get_agent(
- "vim",
- project_id=self.ob_projectid).create(entity=json.dumps(vim_json))
-
- market_agent = self.main_agent.get_agent("market",
- project_id=self.ob_projectid)
-
- nsd = {}
- try:
- self.logger.info("sending: %s", self.market_link)
- nsd = market_agent.create(entity=self.market_link)
- self.logger.info("Onboarded NSD: " + nsd.get("name"))
- except NfvoException as e:
- self.logger.error(e.message)
-
- nsr_agent = self.main_agent.get_agent("nsr",
- project_id=self.ob_projectid)
- nsd_id = nsd.get('id')
- if nsd_id is None:
- self.logger.error("NSD not onboarded correctly")
-
- try:
- self.nsr = nsr_agent.create(nsd_id)
- except NfvoException as e:
- self.logger.error(e.message)
-
- if self.nsr.get('code') is not None:
- self.logger.error(
- "vIMS cannot be deployed: %s -> %s",
- self.nsr.get('code'),
- self.nsr.get('message'))
- self.logger.error("vIMS cannot be deployed")
-
- i = 0
- self.logger.info("Waiting for NSR to go to ACTIVE...")
- while self.nsr.get("status") != 'ACTIVE' and self.nsr.get(
- "status") != 'ERROR':
- i += 1
- if i == 150:
- self.logger.error("INACTIVE NSR after %s sec..", 5 * i)
-
- time.sleep(5)
- self.nsr = json.loads(nsr_agent.find(self.nsr.get('id')))
-
- if self.nsr.get("status") == 'ACTIVE':
- self.details["vnf"] = {'status': "PASS", 'result': self.nsr}
- self.logger.info("Deploy VNF: OK")
- else:
- self.details["vnf"] = {'status': "FAIL", 'result': self.nsr}
- self.logger.error(self.nsr)
- self.logger.error("Deploy VNF: ERROR")
- return False
-
- self.ob_nsr_id = self.nsr.get("id")
- self.logger.info(
- "Sleep for 60s to ensure that all services are up and running...")
- time.sleep(60)
- return True
-
- def test_vnf(self):
- # Adaptations probably needed
- # code used for cloudify_ims
- # ruby client on jumphost calling the vIMS on the SUT
- self.logger.info(
- "Testing if %s works properly...", self.nsr.get('name'))
- for vnfr in self.nsr.get('vnfr'):
- self.logger.info(
- "Checking ports %s of VNF %s",
- self.ims_conf.get(vnfr.get('name')).get('ports'),
- vnfr.get('name'))
- for vdu in vnfr.get('vdu'):
- for vnfci in vdu.get('vnfc_instance'):
- self.logger.debug(
- "Checking ports of VNFC instance %s",
- vnfci.get('hostname'))
- for floatingIp in vnfci.get('floatingIps'):
- self.logger.debug(
- "Testing %s:%s",
- vnfci.get('hostname'),
- floatingIp.get('ip'))
- for port in self.ims_conf.get(
- vnfr.get('name')).get('ports'):
- if servertest(floatingIp.get('ip'), port):
- self.logger.info(
- "VNFC instance %s is reachable at %s:%s",
- vnfci.get('hostname'),
- floatingIp.get('ip'),
- port)
- else:
- self.logger.error(
- "VNFC instance %s is not reachable "
- "at %s:%s",
- vnfci.get('hostname'),
- floatingIp.get('ip'),
- port)
- self.details["test_vnf"] = {
- 'status': "FAIL", 'result': (
- "Port %s of server %s -> %s is "
- "not reachable",
- port,
- vnfci.get('hostname'),
- floatingIp.get('ip'))}
- self.logger.error("Test VNF: ERROR")
- return False
-
- self.details["test_vnf"] = {
- 'status': "PASS",
- 'result': "All tests have been executed successfully"}
- self.logger.info("Test VNF: OK")
- return True
-
- def clean(self):
- self.main_agent.get_agent(
- "nsr",
- project_id=self.ob_projectid).delete(self.ob_nsr_id)
- time.sleep(5)
- os_utils.delete_instance(nova_client=os_utils.get_nova_client(),
- instance_id=self.ob_instance_id)
- # question is the clean removing also the VM?
- # I think so since is goinf to remove the tenant...
- super(ImsVnf, self).clean()
diff --git a/functest/opnfv_tests/vnf/ims/orchestra_ims.yaml b/functest/opnfv_tests/vnf/ims/orchestra_ims.yaml
deleted file mode 100644
index 5b25d3c9..00000000
--- a/functest/opnfv_tests/vnf/ims/orchestra_ims.yaml
+++ /dev/null
@@ -1,21 +0,0 @@
-tenant_images:
- ubuntu_14.04: http://cloud-images.ubuntu.com/trusty/current/trusty-server-cloudimg-amd64-disk1.img
- openims: http://marketplace.openbaton.org:8082/api/v1/images/52e2ccc0-1dce-4663-894d-28aab49323aa/img
-openbaton:
- bootstrap_link: http://get.openbaton.org/bootstraps/bootstrap_3.2.0_opnfv/bootstrap
- bootstrap_config_link: http://get.openbaton.org/bootstraps/bootstrap_3.2.0_opnfv/bootstrap-config-file
- userdata:
- file: https://raw.githubusercontent.com/openbaton/generic-vnfm/3.2.0/src/main/resources/user-data.sh
- marketplace_link: http://marketplace.openbaton.org:8082/api/v1/nsds/fokus/OpenImsCore/3.2.0/json
- imagename: ubuntu_14.04
-vIMS:
- scscf:
- ports: [3870, 6060]
- pcscf:
- ports: [4060]
- icscf:
- ports: [3869, 5060]
- fhoss:
- ports: [3868]
- bind9:
- ports: [] \ No newline at end of file
diff --git a/functest/opnfv_tests/vnf/ims/orchestra_openims.py b/functest/opnfv_tests/vnf/ims/orchestra_openims.py
new file mode 100644
index 00000000..f8acada4
--- /dev/null
+++ b/functest/opnfv_tests/vnf/ims/orchestra_openims.py
@@ -0,0 +1,718 @@
+#!/usr/bin/env python
+
+# Copyright (c) 2016 Orange and others.
+#
+# All rights reserved. This program and the accompanying materials
+# are made available under the terms of the Apache License, Version 2.0
+# which accompanies this distribution, and is available at
+# http://www.apache.org/licenses/LICENSE-2.0
+
+"""Orchestra OpenIMS testcase implementation."""
+
+import json
+import logging
+import os
+import socket
+import time
+import pkg_resources
+import yaml
+
+
+from snaps.openstack.create_image import OpenStackImage, ImageSettings
+from snaps.openstack.create_flavor import OpenStackFlavor, FlavorSettings
+from snaps.openstack.create_security_group import (
+ OpenStackSecurityGroup,
+ SecurityGroupSettings,
+ SecurityGroupRuleSettings,
+ Direction,
+ Protocol)
+from snaps.openstack.create_network import (
+ OpenStackNetwork,
+ NetworkSettings,
+ SubnetSettings,
+ PortSettings)
+from snaps.openstack.create_router import OpenStackRouter, RouterSettings
+from snaps.openstack.os_credentials import OSCreds
+from snaps.openstack.create_instance import (
+ VmInstanceSettings, OpenStackVmInstance)
+from functest.opnfv_tests.openstack.snaps import snaps_utils
+
+import functest.core.vnf as vnf
+import functest.utils.openstack_utils as os_utils
+from functest.utils.constants import CONST
+
+from org.openbaton.cli.errors.errors import NfvoException
+from org.openbaton.cli.agents.agents import MainAgent
+
+
+__author__ = "Pauls, Michael <michael.pauls@fokus.fraunhofer.de>"
+# ----------------------------------------------------------
+#
+# UTILS
+#
+# -----------------------------------------------------------
+
+
+def get_config(parameter, file_path):
+ """
+ Get config parameter.
+
+ Returns the value of a given parameter in file.yaml
+ parameter must be given in string format with dots
+ Example: general.openstack.image_name
+ """
+ with open(file_path) as config_file:
+ file_yaml = yaml.safe_load(config_file)
+ config_file.close()
+ value = file_yaml
+ for element in parameter.split("."):
+ value = value.get(element)
+ if value is None:
+ raise ValueError("The parameter %s is not defined in"
+ " reporting.yaml", parameter)
+ return value
+
+
+def servertest(host, port):
+ """Method to test that a server is reachable at IP:port"""
+ args = socket.getaddrinfo(host, port, socket.AF_INET, socket.SOCK_STREAM)
+ for family, socktype, proto, canonname, sockaddr in args:
+ sock = socket.socket(family, socktype, proto)
+ try:
+ sock.connect(sockaddr)
+ except socket.error:
+ return False
+ else:
+ sock.close()
+ return True
+
+
+def get_userdata(orchestrator=dict):
+ """Build userdata for Open Baton machine"""
+ userdata = "#!/bin/bash\n"
+ userdata += "echo \"Executing userdata...\"\n"
+ userdata += "set -x\n"
+ userdata += "set -e\n"
+ userdata += "echo \"Set nameserver to '8.8.8.8'...\"\n"
+ userdata += "echo \"nameserver 8.8.8.8\" >> /etc/resolv.conf\n"
+ userdata += "echo \"Install curl...\"\n"
+ userdata += "apt-get install curl\n"
+ userdata += "echo \"Inject public key...\"\n"
+ userdata += ("echo \"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCuPXrV3"
+ "geeHc6QUdyUr/1Z+yQiqLcOskiEGBiXr4z76MK4abiFmDZ18OMQlc"
+ "fl0p3kS0WynVgyaOHwZkgy/DIoIplONVr2CKBKHtPK+Qcme2PVnCtv"
+ "EqItl/FcD+1h5XSQGoa+A1TSGgCod/DPo+pes0piLVXP8Ph6QS1k7S"
+ "ic7JDeRQ4oT1bXYpJ2eWBDMfxIWKZqcZRiGPgMIbJ1iEkxbpeaAd9O"
+ "4MiM9nGCPESmed+p54uYFjwEDlAJZShcAZziiZYAvMZhvAhe6USljc"
+ "7YAdalAnyD/jwCHuwIrUw/lxo7UdNCmaUxeobEYyyFA1YVXzpNFZya"
+ "XPGAAYIJwEq/ openbaton@opnfv\" >> /home/ubuntu/.ssh/aut"
+ "horized_keys\n")
+ userdata += "echo \"Download bootstrap...\"\n"
+ userdata += ("curl -s %s "
+ "> ./bootstrap\n" % orchestrator['bootstrap']['url'])
+ userdata += ("curl -s %s" "> ./config_file\n" %
+ orchestrator['bootstrap']['config']['url'])
+ userdata += ("echo \"Disable usage of mysql...\"\n")
+ userdata += "sed -i s/mysql=.*/mysql=no/g /config_file\n"
+ userdata += ("echo \"Setting 'rabbitmq_broker_ip' to '%s'\"\n"
+ % orchestrator['details']['fip'].ip)
+ userdata += ("sed -i s/rabbitmq_broker_ip=localhost/rabbitmq_broker_ip"
+ "=%s/g /config_file\n" % orchestrator['details']['fip'].ip)
+ userdata += "echo \"Set autostart of components to 'false'\"\n"
+ userdata += "export OPENBATON_COMPONENT_AUTOSTART=false\n"
+ userdata += "echo \"Execute bootstrap...\"\n"
+ bootstrap = "sh ./bootstrap release -configFile=./config_file"
+ userdata += bootstrap + "\n"
+ userdata += "echo \"Setting 'nfvo.plugin.timeout' to '300000'\"\n"
+ userdata += ("echo \"nfvo.plugin.timeout=600000\" >> "
+ "/etc/openbaton/openbaton-nfvo.properties\n")
+ userdata += (
+ "wget %s -O /etc/openbaton/openbaton-vnfm-generic-user-data.sh\n" %
+ orchestrator['gvnfm']['userdata']['url'])
+ userdata += "sed -i '113i"'\ \ \ \ '"sleep 60' " \
+ "/etc/openbaton/openbaton-vnfm-generic-user-data.sh\n"
+ userdata += "echo \"Starting NFVO\"\n"
+ userdata += "service openbaton-nfvo restart\n"
+ userdata += "echo \"Starting Generic VNFM\"\n"
+ userdata += "service openbaton-vnfm-generic restart\n"
+ userdata += "echo \"...end of userdata...\"\n"
+ return userdata
+
+
+class OpenImsVnf(vnf.VnfOnBoarding):
+ """OpenIMS VNF deployed with openBaton orchestrator"""
+
+ logger = logging.getLogger(__name__)
+
+ def __init__(self, **kwargs):
+ if "case_name" not in kwargs:
+ kwargs["case_name"] = "orchestra_openims"
+ super(OpenImsVnf, self).__init__(**kwargs)
+ # self.logger = logging.getLogger("functest.ci.run_tests.orchestra")
+ self.logger.info("kwargs %s", (kwargs))
+
+ self.case_dir = pkg_resources.resource_filename(
+ 'functest', 'opnfv_tests/vnf/ims/')
+ self.data_dir = CONST.__getattribute__('dir_ims_data')
+ self.test_dir = CONST.__getattribute__('dir_repo_vims_test')
+ self.created_resources = []
+ self.logger.info("%s VNF onboarding test starting", self.case_name)
+
+ try:
+ self.config = CONST.__getattribute__(
+ 'vnf_{}_config'.format(self.case_name))
+ except BaseException:
+ raise Exception("Orchestra VNF config file not found")
+ config_file = self.case_dir + self.config
+
+ self.mano = dict(
+ get_config("mano", config_file),
+ details={}
+ )
+ self.logger.debug("Orchestrator configuration %s", self.mano)
+
+ self.details['orchestrator'] = dict(
+ name=self.mano['name'],
+ version=self.mano['version'],
+ status='ERROR',
+ result=''
+ )
+
+ self.vnf = dict(
+ get_config(self.case_name, config_file),
+ )
+ self.logger.debug("VNF configuration: %s", self.vnf)
+
+ self.details['vnf'] = dict(
+ name=self.vnf['name'],
+ )
+
+ self.details['test_vnf'] = dict(
+ name=self.case_name,
+ )
+
+ # Orchestra base Data directory creation
+ if not os.path.exists(self.data_dir):
+ os.makedirs(self.data_dir)
+
+ self.images = get_config("tenant_images.orchestrator", config_file)
+ self.images.update(get_config("tenant_images.%s" %
+ self.case_name, config_file))
+ self.snaps_creds = None
+
+ def prepare(self):
+ """Prepare testscase (Additional pre-configuration steps)."""
+ super(OpenImsVnf, self).prepare()
+
+ self.logger.info("Additional pre-configuration steps")
+ self.logger.info("creds %s", (self.creds))
+
+ self.snaps_creds = OSCreds(
+ username=self.creds['username'],
+ password=self.creds['password'],
+ auth_url=self.creds['auth_url'],
+ project_name=self.creds['tenant'],
+ identity_api_version=int(os_utils.get_keystone_client_version()))
+
+ self.prepare_images()
+ self.prepare_flavor()
+ self.prepare_security_groups()
+ self.prepare_network()
+ self.prepare_floating_ip()
+
+ def prepare_images(self):
+ """Upload images if they doen't exist yet"""
+ self.logger.info("Upload images if they doen't exist yet")
+ for image_name, image_file in self.images.iteritems():
+ self.logger.info("image: %s, file: %s", image_name, image_file)
+ if image_file and image_name:
+ image = OpenStackImage(
+ self.snaps_creds,
+ ImageSettings(name=image_name,
+ image_user='cloud',
+ img_format='qcow2',
+ image_file=image_file))
+ image.create()
+ # self.created_resources.append(image);
+
+ def prepare_security_groups(self):
+ """Create Open Baton security group if it doesn't exist yet"""
+ self.logger.info(
+ "Creating security group for Open Baton if not yet existing...")
+ sg_rules = list()
+ sg_rules.append(
+ SecurityGroupRuleSettings(
+ sec_grp_name="orchestra-sec-group-allowall",
+ direction=Direction.ingress,
+ protocol=Protocol.tcp,
+ port_range_min=1,
+ port_range_max=65535))
+ sg_rules.append(
+ SecurityGroupRuleSettings(
+ sec_grp_name="orchestra-sec-group-allowall",
+ direction=Direction.egress,
+ protocol=Protocol.tcp,
+ port_range_min=1,
+ port_range_max=65535))
+ sg_rules.append(
+ SecurityGroupRuleSettings(
+ sec_grp_name="orchestra-sec-group-allowall",
+ direction=Direction.ingress,
+ protocol=Protocol.udp,
+ port_range_min=1,
+ port_range_max=65535))
+ sg_rules.append(
+ SecurityGroupRuleSettings(
+ sec_grp_name="orchestra-sec-group-allowall",
+ direction=Direction.egress,
+ protocol=Protocol.udp,
+ port_range_min=1,
+ port_range_max=65535))
+ sg_rules.append(
+ SecurityGroupRuleSettings(
+ sec_grp_name="orchestra-sec-group-allowall",
+ direction=Direction.ingress,
+ protocol=Protocol.icmp))
+ sg_rules.append(
+ SecurityGroupRuleSettings(
+ sec_grp_name="orchestra-sec-group-allowall",
+ direction=Direction.egress,
+ protocol=Protocol.icmp))
+ # sg_rules.append(
+ # SecurityGroupRuleSettings(
+ # sec_grp_name="orchestra-sec-group-allowall",
+ # direction=Direction.ingress,
+ # protocol=Protocol.icmp,
+ # port_range_min=-1,
+ # port_range_max=-1))
+ # sg_rules.append(
+ # SecurityGroupRuleSettings(
+ # sec_grp_name="orchestra-sec-group-allowall",
+ # direction=Direction.egress,
+ # protocol=Protocol.icmp,
+ # port_range_min=-1,
+ # port_range_max=-1))
+
+ security_group = OpenStackSecurityGroup(
+ self.snaps_creds,
+ SecurityGroupSettings(
+ name="orchestra-sec-group-allowall",
+ rule_settings=sg_rules))
+
+ security_group_info = security_group.create()
+ self.created_resources.append(security_group)
+ self.mano['details']['sec_group'] = security_group_info.name
+ self.logger.info(
+ "Security group orchestra-sec-group-allowall prepared")
+
+ def prepare_flavor(self):
+ """Create Open Baton flavor if it doesn't exist yet"""
+ self.logger.info(
+ "Create Flavor for Open Baton NFVO if not yet existing")
+
+ flavor_settings = FlavorSettings(
+ name=self.mano['requirements']['flavor']['name'],
+ ram=self.mano['requirements']['flavor']['ram_min'],
+ disk=self.mano['requirements']['flavor']['disk'],
+ vcpus=self.mano['requirements']['flavor']['vcpus'])
+ flavor = OpenStackFlavor(self.snaps_creds, flavor_settings)
+ flavor_info = flavor.create()
+ self.created_resources.append(flavor)
+ self.mano['details']['flavor'] = {}
+ self.mano['details']['flavor']['name'] = flavor_settings.name
+ self.mano['details']['flavor']['id'] = flavor_info.id
+
+ def prepare_network(self):
+ """Create network/subnet/router if they doen't exist yet"""
+ self.logger.info(
+ "Creating network/subnet/router if they doen't exist yet...")
+ subnet_settings = SubnetSettings(
+ name='%s_subnet' %
+ self.case_name,
+ cidr="192.168.100.0/24")
+ network_settings = NetworkSettings(
+ name='%s_net' %
+ self.case_name,
+ subnet_settings=[subnet_settings])
+ orchestra_network = OpenStackNetwork(
+ self.snaps_creds, network_settings)
+ orchestra_network_info = orchestra_network.create()
+ self.mano['details']['network'] = {}
+ self.mano['details']['network']['id'] = orchestra_network_info.id
+ self.mano['details']['network']['name'] = orchestra_network_info.name
+ self.mano['details']['external_net_name'] = \
+ snaps_utils.get_ext_net_name(self.snaps_creds)
+ self.created_resources.append(orchestra_network)
+ orchestra_router = OpenStackRouter(
+ self.snaps_creds,
+ RouterSettings(
+ name='%s_router' %
+ self.case_name,
+ external_gateway=self.mano['details']['external_net_name'],
+ internal_subnets=[
+ subnet_settings.name]))
+ orchestra_router.create()
+ self.created_resources.append(orchestra_router)
+ self.logger.info("Created network and router for Open Baton NFVO...")
+
+ def prepare_floating_ip(self):
+ """Select/Create Floating IP if it doesn't exist yet"""
+ self.logger.info("Retrieving floating IP for Open Baton NFVO")
+ neutron_client = snaps_utils.neutron_utils.neutron_client(
+ self.snaps_creds)
+ # Finding Tenant ID to check to which tenant the Floating IP belongs
+ tenant_id = os_utils.get_tenant_id(
+ os_utils.get_keystone_client(self.creds),
+ self.tenant_name)
+ # Use os_utils to retrieve complete information of Floating IPs
+ floating_ips = os_utils.get_floating_ips(neutron_client)
+ my_floating_ips = []
+ # Filter Floating IPs with tenant id
+ for floating_ip in floating_ips:
+ # self.logger.info("Floating IP: %s", floating_ip)
+ if floating_ip.get('tenant_id') == tenant_id:
+ my_floating_ips.append(floating_ip.get('floating_ip_address'))
+ # Select if Floating IP exist else create new one
+ if len(my_floating_ips) >= 1:
+ # Get Floating IP object from snaps for clean up
+ snaps_floating_ips = snaps_utils.neutron_utils.get_floating_ips(
+ neutron_client)
+ for my_floating_ip in my_floating_ips:
+ for snaps_floating_ip in snaps_floating_ips:
+ if snaps_floating_ip.ip == my_floating_ip:
+ self.mano['details']['fip'] = snaps_floating_ip
+ self.logger.info(
+ "Selected floating IP for Open Baton NFVO %s",
+ (self.mano['details']['fip'].ip))
+ break
+ if self.mano['details']['fip'] is not None:
+ break
+ else:
+ self.logger.info("Creating floating IP for Open Baton NFVO")
+ self.mano['details']['fip'] = (
+ snaps_utils.neutron_utils. create_floating_ip(
+ neutron_client, self.mano['details']['external_net_name']))
+ self.logger.info(
+ "Created floating IP for Open Baton NFVO %s",
+ (self.mano['details']['fip'].ip))
+
+ def get_vim_descriptor(self):
+ """"Create VIM descriptor to be used for onboarding"""
+ self.logger.info(
+ "Building VIM descriptor with PoP creds: %s",
+ self.creds)
+ # Depending on API version either tenant ID or project name must be
+ # used
+ if os_utils.is_keystone_v3():
+ self.logger.info(
+ "Using v3 API of OpenStack... -> Using OS_PROJECT_ID")
+ project_id = os_utils.get_tenant_id(
+ os_utils.get_keystone_client(),
+ self.creds.get("project_name"))
+ else:
+ self.logger.info(
+ "Using v2 API of OpenStack... -> Using OS_TENANT_NAME")
+ project_id = self.creds.get("tenant_name")
+ self.logger.debug("VIM project/tenant id: %s", project_id)
+ vim_json = {
+ "name": "vim-instance",
+ "authUrl": self.creds.get("auth_url"),
+ "tenant": project_id,
+ "username": self.creds.get("username"),
+ "password": self.creds.get("password"),
+ "securityGroups": [
+ self.mano['details']['sec_group']
+ ],
+ "type": "openstack",
+ "location": {
+ "name": "opnfv",
+ "latitude": "52.525876",
+ "longitude": "13.314400"
+ }
+ }
+ self.logger.info("Built VIM descriptor: %s", vim_json)
+ return vim_json
+
+ def deploy_orchestrator(self):
+ self.logger.info("Deploying Open Baton...")
+ self.logger.info("Details: %s", self.mano['details'])
+ start_time = time.time()
+
+ self.logger.info("Creating orchestra instance...")
+ userdata = get_userdata(self.mano)
+ self.logger.info("flavor: %s\n"
+ "image: %s\n"
+ "network_id: %s\n",
+ self.mano['details']['flavor']['name'],
+ self.mano['requirements']['image'],
+ self.mano['details']['network']['id'])
+ self.logger.debug("userdata: %s\n", userdata)
+ # setting up image
+ image_settings = ImageSettings(
+ name=self.mano['requirements']['image'],
+ image_user='ubuntu',
+ exists=True)
+ # setting up port
+ port_settings = PortSettings(
+ name='%s_port' % self.case_name,
+ network_name=self.mano['details']['network']['name'])
+ # build configuration of vm
+ orchestra_settings = VmInstanceSettings(
+ name=self.case_name,
+ flavor=self.mano['details']['flavor']['name'],
+ port_settings=[port_settings],
+ security_group_names=[self.mano['details']['sec_group']],
+ userdata=userdata)
+ orchestra_vm = OpenStackVmInstance(self.snaps_creds,
+ orchestra_settings,
+ image_settings)
+
+ orchestra_vm.create()
+ self.created_resources.append(orchestra_vm)
+ self.mano['details']['id'] = orchestra_vm.get_vm_info()['id']
+ self.logger.info(
+ "Created orchestra instance: %s",
+ self.mano['details']['id'])
+
+ self.logger.info("Associating floating ip: '%s' to VM '%s' ",
+ self.mano['details']['fip'].ip,
+ self.case_name)
+ nova_client = os_utils.get_nova_client()
+ if not os_utils.add_floating_ip(
+ nova_client,
+ self.mano['details']['id'],
+ self.mano['details']['fip'].ip):
+ duration = time.time() - start_time
+ self.details["orchestrator"].update(
+ status='FAIL', duration=duration)
+ self.logger.error("Cannot associate floating IP to VM.")
+ return False
+
+ self.logger.info("Waiting for Open Baton NFVO to be up and running...")
+ timeout = 0
+ while timeout < 200:
+ if servertest(
+ self.mano['details']['fip'].ip,
+ "8080"):
+ break
+ else:
+ self.logger.info("Open Baton NFVO is not started yet (%ss)",
+ (timeout * 5))
+ time.sleep(5)
+ timeout += 1
+
+ if timeout >= 200:
+ duration = time.time() - start_time
+ self.details["orchestrator"].update(
+ status='FAIL', duration=duration)
+ self.logger.error("Open Baton is not started correctly")
+ return False
+
+ self.logger.info("Waiting for all components to be up and running...")
+ time.sleep(60)
+ duration = time.time() - start_time
+ self.details["orchestrator"].update(status='PASS', duration=duration)
+ self.logger.info("Deploy Open Baton NFVO: OK")
+ return True
+
+ def deploy_vnf(self):
+ start_time = time.time()
+ self.logger.info("Deploying %s...", self.vnf['name'])
+
+ main_agent = MainAgent(
+ nfvo_ip=self.mano['details']['fip'].ip,
+ nfvo_port=8080,
+ https=False,
+ version=1,
+ username=self.mano['credentials']['username'],
+ password=self.mano['credentials']['password'])
+
+ self.logger.info(
+ "Create %s Flavor if not existing", self.vnf['name'])
+ flavor_settings = FlavorSettings(
+ name=self.vnf['requirements']['flavor']['name'],
+ ram=self.vnf['requirements']['flavor']['ram_min'],
+ disk=self.vnf['requirements']['flavor']['disk'],
+ vcpus=self.vnf['requirements']['flavor']['vcpus'])
+ flavor = OpenStackFlavor(self.snaps_creds, flavor_settings)
+ flavor_info = flavor.create()
+ self.logger.debug("Flavor id: %s", flavor_info.id)
+
+ self.logger.info("Getting project 'default'...")
+ project_agent = main_agent.get_agent("project", "")
+ for project in json.loads(project_agent.find()):
+ if project.get("name") == "default":
+ self.mano['details']['project_id'] = project.get("id")
+ self.logger.info("Found project 'default': %s", project)
+ break
+
+ vim_json = self.get_vim_descriptor()
+ self.logger.info("Registering VIM: %s", vim_json)
+
+ main_agent.get_agent(
+ "vim", project_id=self.mano['details']['project_id']).create(
+ entity=json.dumps(vim_json))
+
+ market_agent = main_agent.get_agent(
+ "market", project_id=self.mano['details']['project_id'])
+
+ try:
+ self.logger.info("sending: %s", self.vnf['descriptor']['url'])
+ nsd = market_agent.create(entity=self.vnf['descriptor']['url'])
+ if nsd.get('id') is None:
+ self.logger.error("NSD not onboarded correctly")
+ duration = time.time() - start_time
+ self.details["vnf"].update(status='FAIL', duration=duration)
+ return False
+ self.mano['details']['nsd_id'] = nsd.get('id')
+ self.logger.info("Onboarded NSD: " + nsd.get("name"))
+
+ nsr_agent = main_agent.get_agent(
+ "nsr", project_id=self.mano['details']['project_id'])
+
+ self.mano['details']['nsr'] = nsr_agent.create(
+ self.mano['details']['nsd_id'])
+ except NfvoException as exc:
+ self.logger.error(exc.message)
+ duration = time.time() - start_time
+ self.details["vnf"].update(status='FAIL', duration=duration)
+ return False
+
+ if self.mano['details']['nsr'].get('code') is not None:
+ self.logger.error(
+ "%s cannot be deployed: %s -> %s",
+ self.vnf['name'],
+ self.mano['details']['nsr'].get('code'),
+ self.mano['details']['nsr'].get('message'))
+ self.logger.error("%s cannot be deployed", self.vnf['name'])
+ duration = time.time() - start_time
+ self.details["vnf"].update(status='FAIL', duration=duration)
+ return False
+
+ timeout = 0
+ self.logger.info("Waiting for NSR to go to ACTIVE...")
+ while self.mano['details']['nsr'].get("status") != 'ACTIVE' \
+ and self.mano['details']['nsr'].get("status") != 'ERROR':
+ timeout += 1
+ self.logger.info("NSR is not yet ACTIVE... (%ss)", 5 * timeout)
+ if timeout == 300:
+ self.logger.error("INACTIVE NSR after %s sec..", 5 * timeout)
+ duration = time.time() - start_time
+ self.details["vnf"].update(status='FAIL', duration=duration)
+ return False
+ time.sleep(5)
+ self.mano['details']['nsr'] = json.loads(
+ nsr_agent.find(self.mano['details']['nsr'].get('id')))
+
+ duration = time.time() - start_time
+ if self.mano['details']['nsr'].get("status") == 'ACTIVE':
+ self.details["vnf"].update(status='PASS', duration=duration)
+ self.logger.info("Sleep for 60s to ensure that all "
+ "services are up and running...")
+ time.sleep(60)
+ result = True
+ else:
+ self.details["vnf"].update(status='FAIL', duration=duration)
+ self.logger.error("NSR: %s", self.mano['details'].get('nsr'))
+ result = False
+ return result
+
+ def test_vnf(self):
+ self.logger.info("Testing VNF OpenIMS...")
+ start_time = time.time()
+ self.logger.info(
+ "Testing if %s works properly...",
+ self.mano['details']['nsr'].get('name'))
+ for vnfr in self.mano['details']['nsr'].get('vnfr'):
+ self.logger.info(
+ "Checking ports %s of VNF %s",
+ self.vnf['test'][vnfr.get('name')]['ports'],
+ vnfr.get('name'))
+ for vdu in vnfr.get('vdu'):
+ for vnfci in vdu.get('vnfc_instance'):
+ self.logger.debug(
+ "Checking ports of VNFC instance %s",
+ vnfci.get('hostname'))
+ for floating_ip in vnfci.get('floatingIps'):
+ self.logger.debug(
+ "Testing %s:%s",
+ vnfci.get('hostname'),
+ floating_ip.get('ip'))
+ for port in self.vnf['test'][vnfr.get(
+ 'name')]['ports']:
+ if servertest(floating_ip.get('ip'), port):
+ self.logger.info(
+ "VNFC instance %s is reachable at %s:%s",
+ vnfci.get('hostname'),
+ floating_ip.get('ip'),
+ port)
+ else:
+ self.logger.error(
+ "VNFC instance %s is not reachable "
+ "at %s:%s",
+ vnfci.get('hostname'),
+ floating_ip.get('ip'),
+ port)
+ duration = time.time() - start_time
+ self.details["test_vnf"].update(
+ status='FAIL', duration=duration, esult=(
+ "Port %s of server %s -> %s is "
+ "not reachable",
+ port,
+ vnfci.get('hostname'),
+ floating_ip.get('ip')))
+ self.logger.error("Test VNF: ERROR")
+ return False
+ duration = time.time() - start_time
+ self.details["test_vnf"].update(status='PASS', duration=duration)
+ self.logger.info("Test VNF: OK")
+ return True
+
+ def clean(self):
+ self.logger.info("Cleaning %s...", self.case_name)
+ try:
+ main_agent = MainAgent(
+ nfvo_ip=self.mano['details']['fip'].ip,
+ nfvo_port=8080,
+ https=False,
+ version=1,
+ username=self.mano['credentials']['username'],
+ password=self.mano['credentials']['password'])
+ self.logger.info("Terminating %s...", self.vnf['name'])
+ if (self.mano['details'].get('nsr')):
+ main_agent.get_agent(
+ "nsr",
+ project_id=self.mano['details']['project_id']).\
+ delete(self.mano['details']['nsr'].get('id'))
+ self.logger.info("Sleeping 60 seconds...")
+ time.sleep(60)
+ else:
+ self.logger.info("No need to terminate the VNF...")
+ # os_utils.delete_instance(nova_client=os_utils.get_nova_client(),
+ # instance_id=self.mano_instance_id)
+ except (NfvoException, KeyError) as exc:
+ self.logger.error('Unexpected error cleaning - %s', exc)
+
+ try:
+ neutron_client = os_utils.get_neutron_client(self.creds)
+ self.logger.info("Deleting Open Baton Port...")
+ port = snaps_utils.neutron_utils.get_port_by_name(
+ neutron_client, '%s_port' % self.case_name)
+ snaps_utils.neutron_utils.delete_port(neutron_client, port)
+ time.sleep(10)
+ except Exception as exc:
+ self.logger.error('Unexpected error cleaning - %s', exc)
+ try:
+ self.logger.info("Deleting Open Baton Floating IP...")
+ snaps_utils.neutron_utils.delete_floating_ip(
+ neutron_client, self.mano['details']['fip'])
+ except Exception as exc:
+ self.logger.error('Unexpected error cleaning - %s', exc)
+
+ for resource in reversed(self.created_resources):
+ try:
+ self.logger.info("Cleaning %s", str(resource))
+ resource.clean()
+ except Exception as exc:
+ self.logger.error('Unexpected error cleaning - %s', exc)
+ super(OpenImsVnf, self).clean()