aboutsummaryrefslogtreecommitdiffstats
path: root/functest/opnfv_tests/vnf/router
diff options
context:
space:
mode:
Diffstat (limited to 'functest/opnfv_tests/vnf/router')
-rw-r--r--functest/opnfv_tests/vnf/router/cloudify_vrouter.py440
-rw-r--r--functest/opnfv_tests/vnf/router/cloudify_vrouter.yaml3
-rw-r--r--functest/opnfv_tests/vnf/router/test_controller/function_test_exec.py20
-rw-r--r--functest/opnfv_tests/vnf/router/utilvnf.py129
-rw-r--r--functest/opnfv_tests/vnf/router/vnf_controller/checker.py2
-rw-r--r--functest/opnfv_tests/vnf/router/vnf_controller/command_generator.py2
-rw-r--r--functest/opnfv_tests/vnf/router/vnf_controller/ssh_client.py8
-rw-r--r--functest/opnfv_tests/vnf/router/vnf_controller/vm_controller.py28
-rw-r--r--functest/opnfv_tests/vnf/router/vnf_controller/vnf_controller.py24
-rw-r--r--functest/opnfv_tests/vnf/router/vrouter_base.py34
10 files changed, 162 insertions, 528 deletions
diff --git a/functest/opnfv_tests/vnf/router/cloudify_vrouter.py b/functest/opnfv_tests/vnf/router/cloudify_vrouter.py
index e56f23cfc..32d675347 100644
--- a/functest/opnfv_tests/vnf/router/cloudify_vrouter.py
+++ b/functest/opnfv_tests/vnf/router/cloudify_vrouter.py
@@ -14,64 +14,54 @@
import logging
import os
import time
-import uuid
-
-from cloudify_rest_client import CloudifyClient
-from cloudify_rest_client.executions import Execution
-from scp import SCPClient
-import six
-from snaps.config.flavor import FlavorConfig
-from snaps.config.image import ImageConfig
-from snaps.config.keypair import KeypairConfig
-from snaps.config.network import NetworkConfig, PortConfig, SubnetConfig
-from snaps.config.router import RouterConfig
-from snaps.config.security_group import (
- Direction, Protocol, SecurityGroupConfig, SecurityGroupRuleConfig)
-from snaps.config.user import UserConfig
-from snaps.config.vm_inst import FloatingIpConfig, VmInstanceConfig
-from snaps.openstack.create_flavor import OpenStackFlavor
-from snaps.openstack.create_image import OpenStackImage
-from snaps.openstack.create_instance import OpenStackVmInstance
-from snaps.openstack.create_keypairs import OpenStackKeypair
-from snaps.openstack.create_network import OpenStackNetwork
-from snaps.openstack.create_security_group import OpenStackSecurityGroup
-from snaps.openstack.create_router import OpenStackRouter
-from snaps.openstack.create_user import OpenStackUser
-import snaps.openstack.utils.glance_utils as glance_utils
-from snaps.openstack.utils import keystone_utils
-
-from functest.opnfv_tests.openstack.snaps import snaps_utils
-import functest.opnfv_tests.vnf.router.vrouter_base as vrouter_base
+
+import pkg_resources
+
+from functest.core import cloudify
+from functest.opnfv_tests.vnf.router import vrouter_base
from functest.opnfv_tests.vnf.router.utilvnf import Utilvnf
from functest.utils import config
from functest.utils import env
from functest.utils import functest_utils
+
__author__ = "Shuya Nakama <shuya.nakama@okinawaopenlabs.org>"
-class CloudifyVrouter(vrouter_base.VrouterOnBoardingBase):
+class CloudifyVrouter(cloudify.Cloudify):
# pylint: disable=too-many-instance-attributes
"""vrouter testcase deployed with Cloudify Orchestrator."""
__logger = logging.getLogger(__name__)
- name = __name__
+
+ filename_alt = '/home/opnfv/functest/images/vyos-1.1.8-amd64.qcow2'
+
+ flavor_alt_ram = 1024
+ flavor_alt_vcpus = 1
+ flavor_alt_disk = 3
+
+ check_console_loop = 12
+
+ cop_yaml = ("https://github.com/cloudify-cosmo/cloudify-openstack-plugin/"
+ "releases/download/2.14.7/plugin.yaml")
+ cop_wgn = ("https://github.com/cloudify-cosmo/cloudify-openstack-plugin/"
+ "releases/download/2.14.7/cloudify_openstack_plugin-2.14.7-py27"
+ "-none-linux_x86_64-centos-Core.wgn")
def __init__(self, **kwargs):
if "case_name" not in kwargs:
kwargs["case_name"] = "vyos_vrouter"
- super(CloudifyVrouter, self).__init__(**kwargs)
+ super().__init__(**kwargs)
# Retrieve the configuration
try:
self.config = getattr(
- config.CONF, 'vnf_{}_config'.format(self.case_name))
- except Exception:
- raise Exception("VNF config file not found")
-
- self.cfy_manager_ip = ''
- self.deployment_name = ''
+ config.CONF, f'vnf_{self.case_name}_config')
+ except Exception as exc:
+ raise Exception("VNF config file not found") from exc
+ self.case_dir = pkg_resources.resource_filename(
+ 'functest', 'opnfv_tests/vnf/router')
config_file = os.path.join(self.case_dir, self.config)
self.orchestrator = dict(
requirements=functest_utils.get_parameter_from_yaml(
@@ -86,7 +76,7 @@ class CloudifyVrouter(vrouter_base.VrouterOnBoardingBase):
result=''
)
self.__logger.debug("Orchestrator configuration %s", self.orchestrator)
- self.__logger.debug("name = %s", self.name)
+ self.__logger.debug("name = %s", __name__)
self.vnf = dict(
descriptor=functest_utils.get_parameter_from_yaml(
"vnf.descriptor", config_file),
@@ -105,6 +95,10 @@ class CloudifyVrouter(vrouter_base.VrouterOnBoardingBase):
self.__logger.debug("VNF configuration: %s", self.vnf)
self.util = Utilvnf()
+ self.util.set_credentials(self.cloud)
+ credentials = {"cloud": self.cloud}
+ self.util_info = {"credentials": credentials,
+ "vnf_data_dir": self.util.vnf_data_dir}
self.details['test_vnf'] = dict(
name=functest_utils.get_parameter_from_yaml(
@@ -116,263 +110,94 @@ class CloudifyVrouter(vrouter_base.VrouterOnBoardingBase):
"tenant_images", config_file)
self.__logger.info("Images needed for vrouter: %s", self.images)
- @staticmethod
- def run_blocking_ssh_command(ssh, cmd,
- error_msg="Unable to run this command"):
- """Command to run ssh command with the exit status."""
- (_, stdout, stderr) = ssh.exec_command(cmd)
- CloudifyVrouter.__logger.debug("SSH %s stdout: %s", cmd, stdout.read())
- if stdout.channel.recv_exit_status() != 0:
- CloudifyVrouter.__logger.error(
- "SSH %s stderr: %s", cmd, stderr.read())
- raise Exception(error_msg)
-
- def prepare(self):
- super(CloudifyVrouter, self).prepare()
- self.__logger.info("Additional pre-configuration steps")
- self.util.set_credentials(self.snaps_creds)
-
- def deploy_orchestrator(self):
+ self.image_alt = None
+ self.flavor_alt = None
+
+ def check_requirements(self):
+ if env.get('NEW_USER_ROLE').lower() == "admin":
+ self.__logger.warning(
+ "Defining NEW_USER_ROLE=admin will easily break the testcase "
+ "because Cloudify doesn't manage tenancy (e.g. subnet "
+ "overlapping)")
+
+ def execute(self):
# pylint: disable=too-many-locals,too-many-statements
"""
Deploy Cloudify Manager.
network, security group, fip, VM creation
"""
# network creation
+ super().execute()
start_time = time.time()
+ self.put_private_key()
+ self.upload_cfy_plugins(self.cop_yaml, self.cop_wgn)
- # orchestrator VM flavor
- self.__logger.info("Get or create flavor for cloudify manager vm ...")
- flavor_settings = FlavorConfig(
- name="{}-{}".format(
- self.orchestrator['requirements']['flavor']['name'],
- self.uuid),
- ram=self.orchestrator['requirements']['flavor']['ram_min'],
- disk=50, vcpus=2)
- flavor_creator = OpenStackFlavor(self.snaps_creds, flavor_settings)
- flavor_creator.create()
- self.created_object.append(flavor_creator)
-
- user_creator = OpenStackUser(
- self.snaps_creds,
- UserConfig(
- name='cloudify_network_bug-{}'.format(self.uuid),
- password=str(uuid.uuid4()),
- project_name=self.tenant_name,
- domain_name=self.snaps_creds.user_domain_name,
- roles={'_member_': self.tenant_name}))
- user_creator.create()
- self.created_object.append(user_creator)
-
- snaps_creds = user_creator.get_os_creds(self.snaps_creds.project_name)
- self.__logger.debug("snaps creds: %s", snaps_creds)
-
- self.__logger.info("Creating keypair ...")
- kp_file = os.path.join(self.data_dir, "cloudify_vrouter.pem")
- keypair_settings = KeypairConfig(
- name='cloudify_vrouter_kp-{}'.format(self.uuid),
- private_filepath=kp_file)
- keypair_creator = OpenStackKeypair(snaps_creds, keypair_settings)
- keypair_creator.create()
- self.created_object.append(keypair_creator)
-
- self.__logger.info("Upload some OS images if it doesn't exist")
- for image_name, image_file in six.iteritems(self.images):
- self.__logger.info("image: %s, file: %s", image_name, image_file)
- if image_file and image_name:
- image_creator = OpenStackImage(
- snaps_creds,
- ImageConfig(
- name=image_name, image_user='cloud',
- img_format='qcow2', image_file=image_file))
- image_creator.create()
- self.created_object.append(image_creator)
-
- self.__logger.info("Creating full network ...")
- subnet_settings = SubnetConfig(
- name='cloudify_vrouter_subnet-{}'.format(self.uuid),
- cidr='10.67.79.0/24',
- dns_nameservers=[env.get('NAMESERVER')])
- network_settings = NetworkConfig(
- name='cloudify_vrouter_network-{}'.format(self.uuid),
- subnet_settings=[subnet_settings])
- network_creator = OpenStackNetwork(snaps_creds, network_settings)
- network_creator.create()
- self.created_object.append(network_creator)
- ext_net_name = snaps_utils.get_ext_net_name(snaps_creds)
- router_creator = OpenStackRouter(
- snaps_creds,
- RouterConfig(
- name='cloudify_vrouter_router-{}'.format(self.uuid),
- external_gateway=ext_net_name,
- internal_subnets=[subnet_settings.name]))
- router_creator.create()
- self.created_object.append(router_creator)
-
- # security group creation
- self.__logger.info("Creating security group for cloudify manager vm")
- sg_rules = list()
- sg_rules.append(
- SecurityGroupRuleConfig(
- sec_grp_name="sg-cloudify-manager-{}".format(self.uuid),
- direction=Direction.ingress,
- protocol=Protocol.tcp, port_range_min=1,
- port_range_max=65535))
- sg_rules.append(
- SecurityGroupRuleConfig(
- sec_grp_name="sg-cloudify-manager-{}".format(self.uuid),
- direction=Direction.ingress,
- protocol=Protocol.udp, port_range_min=1,
- port_range_max=65535))
- security_group_creator = OpenStackSecurityGroup(
- snaps_creds,
- SecurityGroupConfig(
- name="sg-cloudify-manager-{}".format(self.uuid),
- rule_settings=sg_rules))
- security_group_creator.create()
- self.created_object.append(security_group_creator)
-
- image_settings = ImageConfig(
- name=self.orchestrator['requirements']['os_image'],
- image_user='centos', exists=True)
- port_settings = PortConfig(
- name='cloudify_manager_port-{}'.format(self.uuid),
- network_name=network_settings.name)
- manager_settings = VmInstanceConfig(
- name='cloudify_manager-{}'.format(self.uuid),
- flavor=flavor_settings.name,
- port_settings=[port_settings],
- security_group_names=[
- security_group_creator.sec_grp_settings.name],
- floating_ip_settings=[FloatingIpConfig(
- name='cloudify_manager_fip-{}'.format(self.uuid),
- port_name=port_settings.name,
- router_name=router_creator.router_settings.name)])
- manager_creator = OpenStackVmInstance(
- snaps_creds, manager_settings, image_settings,
- keypair_settings)
-
- self.__logger.info("Creating cloudify manager VM")
- manager_creator.create()
- self.created_object.append(manager_creator)
-
- cfy_client = CloudifyClient(
- host=manager_creator.get_floating_ip().ip,
- username='admin', password='admin', tenant='default_tenant',
- api_version='v3')
-
- self.orchestrator['object'] = cfy_client
-
- self.cfy_manager_ip = manager_creator.get_floating_ip().ip
-
- self.__logger.info("Attemps running status of the Manager")
- for loop in range(10):
- try:
- self.__logger.debug(
- "status %s", cfy_client.manager.get_status())
- cfy_status = cfy_client.manager.get_status()['status']
- self.__logger.info(
- "The current manager status is %s", cfy_status)
- if str(cfy_status) != 'running':
- raise Exception("Cloudify Manager isn't up and running")
- break
- except Exception: # pylint: disable=broad-except
- self.logger.info(
- "try %s: Cloudify Manager isn't up and running", loop + 1)
- time.sleep(30)
- else:
- self.logger.error("Cloudify Manager isn't up and running")
- return False
+ self.image_alt = self.publish_image_alt()
+ self.flavor_alt = self.create_flavor_alt()
duration = time.time() - start_time
-
- 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(), socket_timeout=15.0)
- scp.put(kp_file, '~/')
- cmd = "sudo cp ~/cloudify_vrouter.pem /etc/cloudify/"
- self.run_blocking_ssh_command(ssh, cmd)
- cmd = "sudo chmod 444 /etc/cloudify/cloudify_vrouter.pem"
- self.run_blocking_ssh_command(ssh, cmd)
- # cmd2 is badly unpinned by Cloudify
- cmd = "sudo yum install -y gcc python-devel python-cmd2"
- self.run_blocking_ssh_command(
- ssh, cmd, "Unable to install packages on manager")
- else:
- self.__logger.error("Cannot connect to manager")
- return False
-
self.details['orchestrator'].update(status='PASS', duration=duration)
- self.__logger.info("Get or create flavor for vrouter")
- flavor_settings = FlavorConfig(
- name="{}-{}".format(
- self.vnf['requirements']['flavor']['name'],
- self.uuid),
- ram=self.vnf['requirements']['flavor']['ram_min'],
- disk=25, vcpus=1)
- flavor_creator = OpenStackFlavor(self.snaps_creds, flavor_settings)
- flavor = flavor_creator.create()
- self.created_object.append(flavor_creator)
-
- # set image name
- glance = glance_utils.glance_client(snaps_creds)
- image = glance_utils.get_image(glance, "vyos1.1.7")
- self.vnf['inputs'].update(dict(external_network_name=ext_net_name))
- self.vnf['inputs'].update(dict(target_vnf_image_id=image.id))
- self.vnf['inputs'].update(dict(reference_vnf_image_id=image.id))
- self.vnf['inputs'].update(dict(target_vnf_flavor_id=flavor.id))
- self.vnf['inputs'].update(dict(reference_vnf_flavor_id=flavor.id))
self.vnf['inputs'].update(dict(
- keystone_username=snaps_creds.username))
+ external_network_name=self.ext_net.name))
self.vnf['inputs'].update(dict(
- keystone_password=snaps_creds.password))
+ target_vnf_image_id=self.image_alt.id))
self.vnf['inputs'].update(dict(
- keystone_tenant_name=snaps_creds.project_name))
+ reference_vnf_image_id=self.image_alt.id))
self.vnf['inputs'].update(dict(
- keystone_user_domain_name=snaps_creds.user_domain_name))
+ target_vnf_flavor_id=self.flavor_alt.id))
self.vnf['inputs'].update(dict(
- keystone_project_domain_name=snaps_creds.project_domain_name))
+ reference_vnf_flavor_id=self.flavor_alt.id))
self.vnf['inputs'].update(dict(
- region=snaps_creds.region_name if snaps_creds.region_name else (
- 'RegionOne')))
+ keystone_username=self.project.user.name))
self.vnf['inputs'].update(dict(
- keystone_url=keystone_utils.get_endpoint(
- snaps_creds, 'identity')))
-
- credentials = {"snaps_creds": snaps_creds}
- self.util_info = {"credentials": credentials,
- "cfy": cfy_client,
- "vnf_data_dir": self.util.vnf_data_dir}
+ keystone_password=self.project.password))
+ self.vnf['inputs'].update(dict(
+ keystone_tenant_name=self.project.project.name))
+ self.vnf['inputs'].update(dict(
+ keystone_user_domain_name=os.environ.get(
+ 'OS_USER_DOMAIN_NAME', 'Default')))
+ self.vnf['inputs'].update(dict(
+ keystone_project_domain_name=os.environ.get(
+ 'OS_PROJECT_DOMAIN_NAME', 'Default')))
+ self.vnf['inputs'].update(dict(
+ region=os.environ.get('OS_REGION_NAME', 'RegionOne')))
+ self.vnf['inputs'].update(dict(
+ keystone_url=self.get_public_auth_url(self.orig_cloud)))
- return True
+ if self.deploy_vnf() and self.test_vnf():
+ self.result = 100
+ return 0
+ self.result = 1/3 * 100
+ return 1
def deploy_vnf(self):
start_time = time.time()
-
self.__logger.info("Upload VNFD")
- cfy_client = self.orchestrator['object']
descriptor = self.vnf['descriptor']
- self.deployment_name = descriptor.get('name')
+ self.util_info["cfy"] = self.cfy_client
+ self.util_info["cfy_manager_ip"] = self.fip.floating_ip_address
+ self.util_info["deployment_name"] = descriptor.get('name')
- cfy_client.blueprints.upload(
+ self.cfy_client.blueprints.upload(
descriptor.get('file_name'), descriptor.get('name'))
self.__logger.info("Create VNF Instance")
- cfy_client.deployments.create(
+ self.cfy_client.deployments.create(
descriptor.get('name'), descriptor.get('name'),
self.vnf.get('inputs'))
- wait_for_execution(
- cfy_client, get_execution_id(cfy_client, descriptor.get('name')),
+ cloudify.wait_for_execution(
+ self.cfy_client, cloudify.get_execution_id(
+ self.cfy_client, descriptor.get('name')),
self.__logger, timeout=7200)
self.__logger.info("Start the VNF Instance deployment")
- execution = cfy_client.executions.start(descriptor.get('name'),
- 'install')
+ execution = self.cfy_client.executions.start(
+ descriptor.get('name'), 'install')
# Show execution log
- execution = wait_for_execution(cfy_client, execution, self.__logger)
+ execution = cloudify.wait_for_execution(
+ self.cfy_client, execution, self.__logger)
duration = time.time() - start_time
@@ -387,7 +212,8 @@ class CloudifyVrouter(vrouter_base.VrouterOnBoardingBase):
def test_vnf(self):
start_time = time.time()
- result, test_result_data = super(CloudifyVrouter, self).test_vnf()
+ testing = vrouter_base.VrouterOnBoardingBase(self.util, self.util_info)
+ result, test_result_data = testing.test_vnf()
duration = time.time() - start_time
if result:
self.details['test_vnf'].update(
@@ -400,91 +226,9 @@ class CloudifyVrouter(vrouter_base.VrouterOnBoardingBase):
return True
def clean(self):
- try:
- cfy_client = self.orchestrator['object']
- dep_name = self.vnf['descriptor'].get('name')
- # kill existing execution
- self.__logger.info('Deleting the current deployment')
- exec_list = cfy_client.executions.list(dep_name)
- for execution in exec_list:
- if execution['status'] == "started":
- try:
- cfy_client.executions.cancel(
- execution['id'], force=True)
- except Exception: # pylint: disable=broad-except
- self.__logger.warn("Can't cancel the current exec")
-
- execution = cfy_client.executions.start(
- dep_name, 'uninstall', parameters=dict(ignore_failure=True))
-
- 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 Exception: # pylint: disable=broad-except
- self.__logger.exception("Some issue during the undeployment ..")
-
- super(CloudifyVrouter, self).clean()
-
- def get_vnf_info_list(self, target_vnf_name):
- return self.util.get_vnf_info_list(
- self.cfy_manager_ip, self.deployment_name, target_vnf_name)
-
-
-def wait_for_execution(client, execution, logger, timeout=7200, ):
- """Wait for a workflow execution on Cloudify Manager."""
- # if execution already ended - return without waiting
- if execution.status in Execution.END_STATES:
- return execution
-
- if timeout is not None:
- deadline = time.time() + timeout
-
- # Poll for execution status and execution logs, until execution ends
- # and we receive an event of type in WORKFLOW_END_TYPES
- offset = 0
- batch_size = 50
- event_list = []
- execution_ended = False
- while True:
- event_list = client.events.list(
- execution_id=execution.id, _offset=offset, _size=batch_size,
- include_logs=True, sort='@timestamp').items
-
- offset = offset + len(event_list)
- for event in event_list:
- logger.debug(event.get('message'))
-
- if timeout is not None:
- if time.time() > deadline:
- raise RuntimeError(
- 'execution of operation {0} for deployment {1} '
- 'timed out'.format(execution.workflow_id,
- execution.deployment_id))
- else:
- # update the remaining timeout
- timeout = deadline - time.time()
-
- if not execution_ended:
- execution = client.executions.get(execution.id)
- execution_ended = execution.status in Execution.END_STATES
-
- if execution_ended:
- break
-
- time.sleep(5)
-
- return execution
-
-
-def get_execution_id(client, deployment_id):
- """
- Get the execution id of a env preparation.
- network, security group, fip, VM creation
- """
- executions = client.executions.list(deployment_id=deployment_id)
- for execution in executions:
- if execution.workflow_id == 'create_deployment_environment':
- return execution
- raise RuntimeError('Failed to get create_deployment_environment '
- 'workflow execution.'
- 'Available executions: {0}'.format(executions))
+ self.kill_existing_execution(self.vnf['descriptor'].get('name'))
+ if self.image_alt:
+ self.cloud.delete_image(self.image_alt)
+ if self.flavor_alt:
+ self.orig_cloud.delete_flavor(self.flavor_alt.id)
+ super().clean()
diff --git a/functest/opnfv_tests/vnf/router/cloudify_vrouter.yaml b/functest/opnfv_tests/vnf/router/cloudify_vrouter.yaml
index 649cd6ccd..2d98dffa5 100644
--- a/functest/opnfv_tests/vnf/router/cloudify_vrouter.yaml
+++ b/functest/opnfv_tests/vnf/router/cloudify_vrouter.yaml
@@ -3,9 +3,6 @@ tenant_images:
cloudify_manager_4.0:
/home/opnfv/functest/images/cloudify-manager-premium-4.0.1.qcow2
vyos1.1.7: /home/opnfv/functest/images/vyos-1.1.7.img
-test_data:
- url: 'https://github.com/oolorg/opnfv-vnf-data.git'
- branch: 'fraser'
orchestrator:
name: cloudify
version: '4.0'
diff --git a/functest/opnfv_tests/vnf/router/test_controller/function_test_exec.py b/functest/opnfv_tests/vnf/router/test_controller/function_test_exec.py
index be7bee889..9eb3c5d69 100644
--- a/functest/opnfv_tests/vnf/router/test_controller/function_test_exec.py
+++ b/functest/opnfv_tests/vnf/router/test_controller/function_test_exec.py
@@ -12,6 +12,7 @@
"""vrouter function test execution module"""
import logging
+import os
import time
import yaml
@@ -20,7 +21,7 @@ from functest.opnfv_tests.vnf.router.vnf_controller.vnf_controller import (
VnfController)
-class FunctionTestExec(object):
+class FunctionTestExec():
"""vrouter function test execution class"""
logger = logging.getLogger(__name__)
@@ -31,17 +32,16 @@ class FunctionTestExec(object):
credentials = util_info["credentials"]
self.vnf_ctrl = VnfController(util_info)
- test_cmd_map_file = open(self.util.vnf_data_dir +
- self.util.opnfv_vnf_data_dir +
- self.util.command_template_dir +
- self.util.test_cmd_map_yaml_file,
- 'r')
- self.test_cmd_map_yaml = yaml.safe_load(test_cmd_map_file)
- test_cmd_map_file.close()
+ with open(
+ os.path.join(
+ self.util.vnf_data_dir, self.util.command_template_dir,
+ self.util.test_cmd_map_yaml_file),
+ 'r', encoding='utf-8') as test_cmd_map_file:
+ self.test_cmd_map_yaml = yaml.safe_load(test_cmd_map_file)
- self.util.set_credentials(credentials["snaps_creds"])
+ self.util.set_credentials(credentials["cloud"])
- with open(self.util.test_env_config_yaml) as file_fd:
+ with open(self.util.test_env_config_yaml, encoding='utf-8') as file_fd:
test_env_config_yaml = yaml.safe_load(file_fd)
file_fd.close()
diff --git a/functest/opnfv_tests/vnf/router/utilvnf.py b/functest/opnfv_tests/vnf/router/utilvnf.py
index 31e1b9196..111f20c1a 100644
--- a/functest/opnfv_tests/vnf/router/utilvnf.py
+++ b/functest/opnfv_tests/vnf/router/utilvnf.py
@@ -14,13 +14,9 @@
import json
import logging
import os
-import pkg_resources
import requests
import yaml
-from git import Repo
-from snaps.openstack.utils import nova_utils
-
from functest.utils import config
RESULT_SPRIT_INDEX = {
@@ -47,22 +43,19 @@ NUMBER_OF_DIGITS_FOR_AVG_JITTER = 3
NUMBER_OF_DIGITS_FOR_AVG_PKT_LOSS = 1
-class Utilvnf(object): # pylint: disable=too-many-instance-attributes
+class Utilvnf(): # pylint: disable=too-many-instance-attributes
""" Utility class of vrouter testcase """
logger = logging.getLogger(__name__)
def __init__(self):
- self.snaps_creds = ""
self.vnf_data_dir = getattr(config.CONF, 'dir_router_data')
- self.opnfv_vnf_data_dir = "opnfv-vnf-data/"
self.command_template_dir = "command_template/"
self.test_scenario_yaml = "test_scenario.yaml"
test_env_config_yaml_file = "test_env_config.yaml"
self.test_cmd_map_yaml_file = "test_cmd_map.yaml"
self.test_env_config_yaml = os.path.join(
self.vnf_data_dir,
- self.opnfv_vnf_data_dir,
test_env_config_yaml_file)
self.blueprint_dir = "opnfv-vnf-vyos-blueprint/"
@@ -71,29 +64,7 @@ class Utilvnf(object): # pylint: disable=too-many-instance-attributes
if not os.path.exists(self.vnf_data_dir):
os.makedirs(self.vnf_data_dir)
- case_dir = pkg_resources.resource_filename(
- 'functest', 'opnfv_tests/vnf/router')
-
- config_file_name = getattr(
- config.CONF, 'vnf_{}_config'.format("vyos_vrouter"))
-
- config_file = os.path.join(case_dir, config_file_name)
-
- with open(config_file) as file_fd:
- vrouter_config_yaml = yaml.safe_load(file_fd)
- file_fd.close()
-
- test_data = vrouter_config_yaml.get("test_data")
-
- self.logger.debug("Downloading the test data.")
- vrouter_data_path = self.vnf_data_dir + self.opnfv_vnf_data_dir
-
- if not os.path.exists(vrouter_data_path):
- Repo.clone_from(test_data['url'],
- vrouter_data_path,
- branch=test_data['branch'])
-
- with open(self.test_env_config_yaml) as file_fd:
+ with open(self.test_env_config_yaml, encoding='utf-8') as file_fd:
test_env_config_yaml = yaml.safe_load(file_fd)
file_fd.close()
@@ -107,71 +78,27 @@ class Utilvnf(object): # pylint: disable=too-many-instance-attributes
os.remove(self.test_result_json_file)
self.logger.debug("removed %s", self.test_result_json_file)
- def get_nova_client(self):
- nova_client = nova_utils.nova_client(self.snaps_creds)
-
- return nova_client
+ self.cloud = None
- def set_credentials(self, snaps_creds):
- self.snaps_creds = snaps_creds
+ def set_credentials(self, cloud):
+ self.cloud = cloud
def get_address(self, server_name, network_name):
- nova_client = self.get_nova_client()
- servers_list = nova_client.servers.list()
- server = None
-
- for server in servers_list:
- if server.name == server_name:
- break
-
+ server = self.cloud.get_server(server_name)
address = server.addresses[
network_name][NOVA_CILENT_NETWORK_INFO_INDEX]["addr"]
return address
def get_mac_address(self, server_name, network_name):
- nova_client = self.get_nova_client()
- servers_list = nova_client.servers.list()
- server = None
-
- for server in servers_list:
- if server.name == server_name:
- break
-
+ server = self.cloud.get_server(server_name)
mac_address = server.addresses[network_name][
NOVA_CILENT_NETWORK_INFO_INDEX]["OS-EXT-IPS-MAC:mac_addr"]
return mac_address
- def reboot_vm(self, server_name):
- nova_client = self.get_nova_client()
- servers_list = nova_client.servers.list()
- server = None
-
- for server in servers_list:
- if server.name == server_name:
- break
-
- server.reboot()
-
- return
-
- def delete_vm(self, server_name):
- nova_client = self.get_nova_client()
- servers_list = nova_client.servers.list()
- server = None
-
- for server in servers_list:
- if server.name == server_name:
- nova_client.servers.delete(server)
- break
-
- return
-
def get_blueprint_outputs(self, cfy_manager_ip, deployment_name):
- url = "http://%s/deployments/%s/outputs" % (
- cfy_manager_ip, deployment_name)
-
+ url = f"http://{cfy_manager_ip}/deployments/{deployment_name}/outputs"
response = requests.get(
url,
auth=requests.auth.HTTPBasicAuth('admin', 'admin'),
@@ -200,15 +127,10 @@ class Utilvnf(object): # pylint: disable=too-many-instance-attributes
network_list.append(networks[network_name])
return network_list
- def request_vnf_reboot(self, vnf_info_list):
- for vnf in vnf_info_list:
- self.logger.debug("reboot the %s", vnf["vnf_name"])
- self.reboot_vm(vnf["vnf_name"])
-
def request_vm_delete(self, vnf_info_list):
for vnf in vnf_info_list:
self.logger.debug("delete the %s", vnf["vnf_name"])
- self.delete_vm(vnf["vnf_name"])
+ self.cloud.delete_server(vnf["vnf_name"])
def get_vnf_info_list(self, cfy_manager_ip, topology_deploy_name,
target_vnf_name):
@@ -288,24 +210,29 @@ class Utilvnf(object): # pylint: disable=too-many-instance-attributes
def write_result_data(self, result_data):
test_result = []
if not os.path.isfile(self.test_result_json_file):
- file_fd = open(self.test_result_json_file, "w")
- file_fd.close()
+ with open(
+ self.test_result_json_file, "w",
+ encoding="utf-8") as file_fd:
+ pass
else:
- file_fd = open(self.test_result_json_file, "r")
- test_result = json.load(file_fd)
- file_fd.close()
+ with open(
+ self.test_result_json_file, "r",
+ encoding="utf-8") as file_fd:
+ test_result = json.load(file_fd)
test_result.append(result_data)
- file_fd = open(self.test_result_json_file, "w")
- json.dump(test_result, file_fd)
- file_fd.close()
+ with open(
+ self.test_result_json_file, "w",
+ encoding="utf-8") as file_fd:
+ json.dump(test_result, file_fd)
def output_test_result_json(self):
if os.path.isfile(self.test_result_json_file):
- file_fd = open(self.test_result_json_file, "r")
- test_result = json.load(file_fd)
- file_fd.close()
+ with open(
+ self.test_result_json_file, "r",
+ encoding="utf-8") as file_fd:
+ test_result = json.load(file_fd)
output_json_data = json.dumps(test_result,
sort_keys=True,
indent=4)
@@ -315,8 +242,6 @@ class Utilvnf(object): # pylint: disable=too-many-instance-attributes
@staticmethod
def get_test_scenario(file_path):
- test_scenario_file = open(file_path,
- 'r')
- test_scenario_yaml = yaml.safe_load(test_scenario_file)
- test_scenario_file.close()
+ with open(file_path, "r", encoding="utf-8") as test_scenario_file:
+ test_scenario_yaml = yaml.safe_load(test_scenario_file)
return test_scenario_yaml["test_scenario_list"]
diff --git a/functest/opnfv_tests/vnf/router/vnf_controller/checker.py b/functest/opnfv_tests/vnf/router/vnf_controller/checker.py
index a7a70f6d7..d3a216ed0 100644
--- a/functest/opnfv_tests/vnf/router/vnf_controller/checker.py
+++ b/functest/opnfv_tests/vnf/router/vnf_controller/checker.py
@@ -18,7 +18,7 @@ import re
from jinja2 import Environment, FileSystemLoader
-class Checker(object):
+class Checker():
"""vrouter test result check class"""
logger = logging.getLogger(__name__)
diff --git a/functest/opnfv_tests/vnf/router/vnf_controller/command_generator.py b/functest/opnfv_tests/vnf/router/vnf_controller/command_generator.py
index 7d9116bcc..a86a16485 100644
--- a/functest/opnfv_tests/vnf/router/vnf_controller/command_generator.py
+++ b/functest/opnfv_tests/vnf/router/vnf_controller/command_generator.py
@@ -15,7 +15,7 @@ import logging
from jinja2 import Environment, FileSystemLoader
-class CommandGenerator(object):
+class CommandGenerator():
"""command generator class for vrouter testing"""
logger = logging.getLogger(__name__)
diff --git a/functest/opnfv_tests/vnf/router/vnf_controller/ssh_client.py b/functest/opnfv_tests/vnf/router/vnf_controller/ssh_client.py
index c5f554cbd..269f6526b 100644
--- a/functest/opnfv_tests/vnf/router/vnf_controller/ssh_client.py
+++ b/functest/opnfv_tests/vnf/router/vnf_controller/ssh_client.py
@@ -24,7 +24,7 @@ DEFAULT_CONNECT_RETRY_COUNT = 10
DEFAULT_SEND_TIMEOUT = 10
-class SshClient(object): # pylint: disable=too-many-instance-attributes
+class SshClient(): # pylint: disable=too-many-instance-attributes
"""ssh client class for vrouter testing"""
logger = logging.getLogger(__name__)
@@ -43,7 +43,7 @@ class SshClient(object): # pylint: disable=too-many-instance-attributes
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.util = Utilvnf()
- with open(self.util.test_env_config_yaml) as file_fd:
+ with open(self.util.test_env_config_yaml, encoding='utf-8') as file_fd:
test_env_config_yaml = yaml.safe_load(file_fd)
file_fd.close()
@@ -80,7 +80,7 @@ class SshClient(object): # pylint: disable=too-many-instance-attributes
retrycount -= 1
if retrycount == 0:
- self.logger.warn(
+ self.logger.warning(
"Cannot establish connection to IP '%s'", self.ip_address)
self.connected = False
return self.connected
@@ -110,7 +110,7 @@ class SshClient(object): # pylint: disable=too-many-instance-attributes
cmd)
break
- res_buff += res
+ res_buff += res.decode("utf-8")
self.logger.debug("Response : '%s'", res_buff)
return res_buff
diff --git a/functest/opnfv_tests/vnf/router/vnf_controller/vm_controller.py b/functest/opnfv_tests/vnf/router/vnf_controller/vm_controller.py
index 79acc776f..2210b3909 100644
--- a/functest/opnfv_tests/vnf/router/vnf_controller/vm_controller.py
+++ b/functest/opnfv_tests/vnf/router/vnf_controller/vm_controller.py
@@ -23,7 +23,7 @@ from functest.opnfv_tests.vnf.router.vnf_controller.ssh_client import (
SshClient)
-class VmController(object):
+class VmController():
"""vm controll class"""
logger = logging.getLogger(__name__)
@@ -34,14 +34,12 @@ class VmController(object):
credentials = util_info["credentials"]
self.util = Utilvnf()
- self.util.set_credentials(credentials["snaps_creds"])
+ self.util.set_credentials(credentials["cloud"])
- with open(self.util.test_env_config_yaml) as file_fd:
+ with open(self.util.test_env_config_yaml, encoding='utf-8') as file_fd:
test_env_config_yaml = yaml.safe_load(file_fd)
file_fd.close()
- self.reboot_wait = test_env_config_yaml.get("general").get(
- "reboot_wait")
self.command_wait = test_env_config_yaml.get("general").get(
"command_wait")
self.ssh_connect_timeout = test_env_config_yaml.get("general").get(
@@ -85,16 +83,10 @@ class VmController(object):
result = ssh.connect(self.ssh_connect_timeout,
self.ssh_connect_retry_count)
if not result:
- self.logger.warn("Reboot %s", vm_info["vnf_name"])
- self.util.reboot_vm(vm_info["vnf_name"])
- time.sleep(self.reboot_wait)
- result = ssh.connect(self.ssh_connect_timeout,
- self.ssh_connect_retry_count)
- if not result:
- self.logger.error(
- "Cannot establish connection to IP '%s'. Aborting!",
- ssh.ip_address)
- return None
+ self.logger.error(
+ "Cannot establish connection to IP '%s'. Aborting!",
+ ssh.ip_address)
+ return None
(result, _) = self.command_create_and_execute(
ssh,
@@ -109,10 +101,8 @@ class VmController(object):
def command_create_and_execute(self, ssh, test_cmd_file_path,
cmd_input_param, prompt_file_path):
- prompt_file = open(prompt_file_path,
- 'r')
- prompt = yaml.safe_load(prompt_file)
- prompt_file.close()
+ with open(prompt_file_path, 'r', encoding='utf-8') as prompt_file:
+ prompt = yaml.safe_load(prompt_file)
config_mode_prompt = prompt["config_mode"]
commands = self.command_gen_from_template(test_cmd_file_path,
diff --git a/functest/opnfv_tests/vnf/router/vnf_controller/vnf_controller.py b/functest/opnfv_tests/vnf/router/vnf_controller/vnf_controller.py
index a5b1ad856..46584456f 100644
--- a/functest/opnfv_tests/vnf/router/vnf_controller/vnf_controller.py
+++ b/functest/opnfv_tests/vnf/router/vnf_controller/vnf_controller.py
@@ -26,7 +26,7 @@ from functest.opnfv_tests.vnf.router.vnf_controller.vm_controller import (
VmController)
-class VnfController(object):
+class VnfController():
"""vrouter controll class"""
logger = logging.getLogger(__name__)
@@ -36,7 +36,7 @@ class VnfController(object):
self.util = Utilvnf()
self.vm_controller = VmController(util_info)
- with open(self.util.test_env_config_yaml) as file_fd:
+ with open(self.util.test_env_config_yaml, encoding='utf-8') as file_fd:
test_env_config_yaml = yaml.safe_load(file_fd)
file_fd.close()
@@ -49,10 +49,9 @@ class VnfController(object):
def config_vnf(self, source_vnf, destination_vnf, test_cmd_file_path,
parameter_file_path, prompt_file_path):
# pylint: disable=too-many-arguments
- parameter_file = open(parameter_file_path,
- 'r')
- cmd_input_param = yaml.safe_load(parameter_file)
- parameter_file.close()
+ with open(
+ parameter_file_path, 'r', encoding='utf-8') as parameter_file:
+ cmd_input_param = yaml.safe_load(parameter_file)
cmd_input_param["macaddress"] = source_vnf["data_plane_network_mac"]
cmd_input_param["source_ip"] = source_vnf["data_plane_network_ip"]
@@ -71,19 +70,16 @@ class VnfController(object):
res_dict_data_list = []
- parameter_file = open(parameter_file_path,
- 'r')
- cmd_input_param = yaml.safe_load(parameter_file)
- parameter_file.close()
+ with open(
+ parameter_file_path, 'r', encoding='utf-8') as parameter_file:
+ cmd_input_param = yaml.safe_load(parameter_file)
cmd_input_param["source_ip"] = target_vnf["data_plane_network_ip"]
cmd_input_param["destination_ip"] = reference_vnf[
"data_plane_network_ip"]
- prompt_file = open(prompt_file_path,
- 'r')
- prompt = yaml.safe_load(prompt_file)
- prompt_file.close()
+ with open(prompt_file_path, 'r', encoding='utf-8') as prompt_file:
+ prompt = yaml.safe_load(prompt_file)
terminal_mode_prompt = prompt["terminal_mode"]
ssh = SshClient(target_vnf["floating_ip"],
diff --git a/functest/opnfv_tests/vnf/router/vrouter_base.py b/functest/opnfv_tests/vnf/router/vrouter_base.py
index 6c4e5ce0d..932770b9c 100644
--- a/functest/opnfv_tests/vnf/router/vrouter_base.py
+++ b/functest/opnfv_tests/vnf/router/vrouter_base.py
@@ -19,37 +19,22 @@ import time
import pkg_resources
-import functest.core.vnf as vnf
-from functest.utils import config
from functest.opnfv_tests.vnf.router.test_controller import function_test_exec
-from functest.opnfv_tests.vnf.router.utilvnf import Utilvnf
__author__ = "Shuya Nakama <shuya.nakama@okinawaopenlabs.org>"
-REBOOT_WAIT = 30
-
-class VrouterOnBoardingBase(vnf.VnfOnBoarding):
+class VrouterOnBoardingBase():
"""vrouter testing base class"""
- def __init__(self, **kwargs):
+ def __init__(self, util, util_info):
self.logger = logging.getLogger(__name__)
- super(VrouterOnBoardingBase, self).__init__(**kwargs)
self.case_dir = pkg_resources.resource_filename(
'functest', 'opnfv_tests/vnf/router')
- self.data_dir = getattr(config.CONF, 'dir_router_data')
- self.result_dir = os.path.join(getattr(config.CONF, 'dir_results'),
- self.case_name)
- self.util = Utilvnf()
- self.util_info = {}
-
+ self.util = util
+ self.util_info = util_info
self.vnf_list = []
- if not os.path.exists(self.data_dir):
- os.makedirs(self.data_dir)
- if not os.path.exists(self.result_dir):
- os.makedirs(self.result_dir)
-
def test_vnf(self):
"""vrouter test execution"""
result = False
@@ -89,10 +74,6 @@ class VrouterOnBoardingBase(vnf.VnfOnBoarding):
vnf_info_list = self.get_vnf_info_list(target_vnf_name)
self.vnf_list = vnf_info_list
- self.logger.debug("request vnf's reboot.")
- self.util.request_vnf_reboot(vnf_info_list)
- time.sleep(REBOOT_WAIT)
-
target_vnf = self.util.get_target_vnf(vnf_info_list)
reference_vnf_list = self.util.get_reference_vnf_list(vnf_info_list)
@@ -117,6 +98,7 @@ class VrouterOnBoardingBase(vnf.VnfOnBoarding):
return result, test_result_data
def get_vnf_info_list(self, target_vnf_name):
- # pylint: disable=unused-argument,no-self-use
- vnf_info_list = []
- return vnf_info_list
+ return self.util.get_vnf_info_list(
+ self.util_info["cfy_manager_ip"],
+ self.util_info["deployment_name"],
+ target_vnf_name)