diff options
Diffstat (limited to 'yardstick')
86 files changed, 4493 insertions, 1435 deletions
diff --git a/yardstick/benchmark/contexts/base.py b/yardstick/benchmark/contexts/base.py index ae8319e37..692c16892 100644 --- a/yardstick/benchmark/contexts/base.py +++ b/yardstick/benchmark/contexts/base.py @@ -6,17 +6,20 @@ # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 ############################################################################## + import abc import six -import yardstick.common.utils as utils +from yardstick.common import constants +from yardstick.common import utils class Flags(object): """Class to represent the status of the flags in a context""" _FLAGS = {'no_setup': False, - 'no_teardown': False} + 'no_teardown': False, + 'os_cloud_config': constants.OS_CLOUD_DEFAULT_CONFIG} def __init__(self, **kwargs): for name, value in self._FLAGS.items(): diff --git a/yardstick/benchmark/contexts/heat.py b/yardstick/benchmark/contexts/heat.py index 0d1dfb86f..82861829e 100644 --- a/yardstick/benchmark/contexts/heat.py +++ b/yardstick/benchmark/contexts/heat.py @@ -7,9 +7,6 @@ # http://www.apache.org/licenses/LICENSE-2.0 ############################################################################## -from __future__ import absolute_import -from __future__ import print_function - import collections import logging import os @@ -328,8 +325,10 @@ class HeatContext(Context): if not os.path.exists(self.key_filename): SSH.gen_keys(self.key_filename) - heat_template = HeatTemplate(self.name, self.template_file, - self.heat_parameters) + heat_template = HeatTemplate( + self.name, template_file=self.template_file, + heat_parameters=self.heat_parameters, + os_cloud_config=self._flags.os_cloud_config) if self.template_file is None: self._add_resources_to_template(heat_template) diff --git a/yardstick/benchmark/contexts/standalone/model.py b/yardstick/benchmark/contexts/standalone/model.py index 14738da8a..4d43f2611 100644 --- a/yardstick/benchmark/contexts/standalone/model.py +++ b/yardstick/benchmark/contexts/standalone/model.py @@ -12,7 +12,6 @@ # See the License for the specific language governing permissions and # limitations under the License. -from __future__ import absolute_import import os import re import time @@ -25,11 +24,12 @@ from netaddr import IPNetwork import xml.etree.ElementTree as ET from yardstick import ssh -from yardstick.common.constants import YARDSTICK_ROOT_PATH +from yardstick.common import constants +from yardstick.common import exceptions from yardstick.common.yaml_loader import yaml_load from yardstick.network_services.utils import PciAddress from yardstick.network_services.helpers.cpu import CpuSysCores -from yardstick.common.utils import write_file + LOG = logging.getLogger(__name__) @@ -106,12 +106,17 @@ class Libvirt(object): @staticmethod def virsh_create_vm(connection, cfg): - err = connection.execute("virsh create %s" % cfg)[0] - LOG.info("VM create status: %s", err) + LOG.info('VM create, XML config: %s', cfg) + status, _, error = connection.execute('virsh create %s' % cfg) + if status: + raise exceptions.LibvirtCreateError(error=error) @staticmethod def virsh_destroy_vm(vm_name, connection): - connection.execute("virsh destroy %s" % vm_name) + LOG.info('VM destroy, VM name: %s', vm_name) + status, _, error = connection.execute('virsh destroy %s' % vm_name) + if status: + LOG.warning('Error destroying VM %s. Error: %s', vm_name, error) @staticmethod def _add_interface_address(interface, pci_address): @@ -132,7 +137,7 @@ class Libvirt(object): return vm_pci @classmethod - def add_ovs_interface(cls, vpath, port_num, vpci, vports_mac, xml): + def add_ovs_interface(cls, vpath, port_num, vpci, vports_mac, xml_str): """Add a DPDK OVS 'interface' XML node in 'devices' node <devices> @@ -156,7 +161,7 @@ class Libvirt(object): vhost_path = ('{0}/var/run/openvswitch/dpdkvhostuser{1}'. format(vpath, port_num)) - root = ET.parse(xml) + root = ET.fromstring(xml_str) pci_address = PciAddress(vpci.strip()) device = root.find('devices') @@ -181,10 +186,10 @@ class Libvirt(object): cls._add_interface_address(interface, pci_address) - root.write(xml) + return ET.tostring(root) @classmethod - def add_sriov_interfaces(cls, vm_pci, vf_pci, vf_mac, xml): + def add_sriov_interfaces(cls, vm_pci, vf_pci, vf_mac, xml_str): """Add a SR-IOV 'interface' XML node in 'devices' node <devices> @@ -207,7 +212,7 @@ class Libvirt(object): -sr_iov-how_sr_iov_libvirt_works """ - root = ET.parse(xml) + root = ET.fromstring(xml_str) device = root.find('devices') interface = ET.SubElement(device, 'interface') @@ -224,20 +229,47 @@ class Libvirt(object): pci_vm_address = PciAddress(vm_pci.strip()) cls._add_interface_address(interface, pci_vm_address) - root.write(xml) + return ET.tostring(root) @staticmethod - def create_snapshot_qemu(connection, index, vm_image): - # build snapshot image - image = "/var/lib/libvirt/images/%s.qcow2" % index - connection.execute("rm %s" % image) - qemu_template = "qemu-img create -f qcow2 -o backing_file=%s %s" - connection.execute(qemu_template % (vm_image, image)) + def create_snapshot_qemu(connection, index, base_image): + """Create the snapshot image for a VM using a base image - return image + :param connection: SSH connection to the remote host + :param index: index of the VM to be spawn + :param base_image: path of the VM base image in the remote host + :return: snapshot image path + """ + vm_image = '/var/lib/libvirt/images/%s.qcow2' % index + connection.execute('rm -- "%s"' % vm_image) + status, _, _ = connection.execute('test -r %s' % base_image) + if status: + if not os.access(base_image, os.R_OK): + raise exceptions.LibvirtQemuImageBaseImageNotPresent( + vm_image=vm_image, base_image=base_image) + # NOTE(ralonsoh): done in two steps to avoid root permission + # issues. + LOG.info('Copy %s from execution host to remote host', base_image) + file_name = os.path.basename(os.path.normpath(base_image)) + connection.put_file(base_image, '/tmp/%s' % file_name) + status, _, error = connection.execute( + 'mv -- "/tmp/%s" "%s"' % (file_name, base_image)) + if status: + raise exceptions.LibvirtQemuImageCreateError( + vm_image=vm_image, base_image=base_image, error=error) + + LOG.info('Convert image %s to %s', base_image, vm_image) + qemu_cmd = ('qemu-img create -f qcow2 -o backing_file=%s %s' % + (base_image, vm_image)) + status, _, error = connection.execute(qemu_cmd) + if status: + raise exceptions.LibvirtQemuImageCreateError( + vm_image=vm_image, base_image=base_image, error=error) + return vm_image @classmethod - def build_vm_xml(cls, connection, flavor, cfg, vm_name, index): + def build_vm_xml(cls, connection, flavor, vm_name, index): + """Build the XML from the configuration parameters""" memory = flavor.get('ram', '4096') extra_spec = flavor.get('extra_specs', {}) cpu = extra_spec.get('hw:cpu_cores', '2') @@ -261,9 +293,7 @@ class Libvirt(object): socket=socket, threads=threads, vm_image=image, cpuset=cpuset, cputune=cputune) - write_file(cfg, vm_xml) - - return [vcpu, mac] + return vm_xml, mac @staticmethod def update_interrupts_hugepages_perf(connection): @@ -283,6 +313,13 @@ class Libvirt(object): cpuset = "%s,%s" % (cores, threads) return cpuset + @classmethod + def write_file(cls, file_name, xml_str): + """Dump a XML string to a file""" + root = ET.fromstring(xml_str) + et = ET.ElementTree(element=root) + et.write(file_name, encoding='utf-8', method='xml') + class StandaloneContextHelper(object): """ This class handles all the common code for standalone @@ -374,7 +411,8 @@ class StandaloneContextHelper(object): except IOError as io_error: if io_error.errno != errno.ENOENT: raise - self.file_path = os.path.join(YARDSTICK_ROOT_PATH, file_path) + self.file_path = os.path.join(constants.YARDSTICK_ROOT_PATH, + file_path) cfg = self.read_config_file() nodes.extend([node for node in cfg["nodes"] if str(node["role"]) != nfvi_role]) @@ -506,7 +544,7 @@ class OvsDeploy(object): StandaloneContextHelper.install_req_libs(self.connection, pkgs) def ovs_deploy(self): - ovs_deploy = os.path.join(YARDSTICK_ROOT_PATH, + ovs_deploy = os.path.join(constants.YARDSTICK_ROOT_PATH, "yardstick/resources/scripts/install/", self.OVS_DEPLOY_SCRIPT) if os.path.isfile(ovs_deploy): @@ -522,4 +560,6 @@ class OvsDeploy(object): cmd = "sudo -E %s --ovs='%s' --dpdk='%s' -p='%s'" % (remote_ovs_deploy, ovs, dpdk, http_proxy) - self.connection.execute(cmd) + exit_status, _, stderr = self.connection.execute(cmd) + if exit_status: + raise exceptions.OVSDeployError(stderr=stderr) diff --git a/yardstick/benchmark/contexts/standalone/ovs_dpdk.py b/yardstick/benchmark/contexts/standalone/ovs_dpdk.py index a18b42ea5..b9e66a481 100644 --- a/yardstick/benchmark/contexts/standalone/ovs_dpdk.py +++ b/yardstick/benchmark/contexts/standalone/ovs_dpdk.py @@ -12,26 +12,25 @@ # See the License for the specific language governing permissions and # limitations under the License. -from __future__ import absolute_import -import os -import logging +import io import collections +import logging +import os +import re import time -from collections import OrderedDict - from yardstick import ssh from yardstick.network_services.utils import get_nsb_option -from yardstick.network_services.utils import provision_tool from yardstick.benchmark.contexts.base import Context -from yardstick.benchmark.contexts.standalone.model import Libvirt -from yardstick.benchmark.contexts.standalone.model import StandaloneContextHelper -from yardstick.benchmark.contexts.standalone.model import Server -from yardstick.benchmark.contexts.standalone.model import OvsDeploy -from yardstick.network_services.utils import PciAddress +from yardstick.benchmark.contexts.standalone import model +from yardstick.common import exceptions +from yardstick.network_services import utils + LOG = logging.getLogger(__name__) +MAIN_BRIDGE = 'br0' + class OvsDpdkContext(Context): """ This class handles OVS standalone nodes - VM running on Non-Managed NFVi @@ -50,14 +49,15 @@ class OvsDpdkContext(Context): } DEFAULT_OVS = '2.6.0' - - PKILL_TEMPLATE = "pkill %s %s" + CMD_TIMEOUT = 30 + DEFAULT_USER_PATH = '/usr/local' def __init__(self): self.file_path = None self.sriov = [] self.first_run = True - self.dpdk_devbind = '' + self.dpdk_devbind = os.path.join(get_nsb_option('bin_path'), + 'dpdk-devbind.py') self.vm_names = [] self.nfvi_host = [] self.nodes = [] @@ -65,8 +65,8 @@ class OvsDpdkContext(Context): self.attrs = {} self.vm_flavor = None self.servers = None - self.helper = StandaloneContextHelper() - self.vnf_node = Server() + self.helper = model.StandaloneContextHelper() + self.vnf_node = model.Server() self.ovs_properties = {} self.wait_for_vswitchd = 10 super(OvsDpdkContext, self).__init__() @@ -93,34 +93,32 @@ class OvsDpdkContext(Context): LOG.debug("Networks: %r", self.networks) def setup_ovs(self): - vpath = self.ovs_properties.get("vpath", "/usr/local") - xargs_kill_cmd = self.PKILL_TEMPLATE % ('-9', 'ovs') - + """Initialize OVS-DPDK""" + vpath = self.ovs_properties.get('vpath', self.DEFAULT_USER_PATH) create_from = os.path.join(vpath, 'etc/openvswitch/conf.db') create_to = os.path.join(vpath, 'share/openvswitch/vswitch.ovsschema') cmd_list = [ - "chmod 0666 /dev/vfio/*", - "chmod a+x /dev/vfio", - "pkill -9 ovs", - xargs_kill_cmd, - "killall -r 'ovs*'", - "mkdir -p {0}/etc/openvswitch".format(vpath), - "mkdir -p {0}/var/run/openvswitch".format(vpath), - "rm {0}/etc/openvswitch/conf.db".format(vpath), - "ovsdb-tool create {0} {1}".format(create_from, create_to), - "modprobe vfio-pci", - "chmod a+x /dev/vfio", - "chmod 0666 /dev/vfio/*", + 'killall -r "ovs.*" -q | true', + 'mkdir -p {0}/etc/openvswitch'.format(vpath), + 'mkdir -p {0}/var/run/openvswitch'.format(vpath), + 'rm {0}/etc/openvswitch/conf.db | true'.format(vpath), + 'ovsdb-tool create {0} {1}'.format(create_from, create_to), + 'modprobe vfio-pci', + 'chmod a+x /dev/vfio', + 'chmod 0666 /dev/vfio/*', ] - for cmd in cmd_list: - self.connection.execute(cmd) - bind_cmd = "{dpdk_devbind} --force -b {driver} {port}" - phy_driver = "vfio-pci" + + bind_cmd = '%s --force -b vfio-pci {port}' % self.dpdk_devbind for port in self.networks.values(): - vpci = port.get("phy_port") - self.connection.execute(bind_cmd.format( - dpdk_devbind=self.dpdk_devbind, driver=phy_driver, port=vpci)) + cmd_list.append(bind_cmd.format(port=port.get('phy_port'))) + + for cmd in cmd_list: + LOG.info(cmd) + exit_status, _, stderr = self.connection.execute( + cmd, timeout=self.CMD_TIMEOUT) + if exit_status: + raise exceptions.OVSSetupError(command=cmd, error=stderr) def start_ovs_serverswitch(self): vpath = self.ovs_properties.get("vpath") @@ -166,56 +164,78 @@ class OvsDpdkContext(Context): vpath = self.ovs_properties.get("vpath", "/usr/local") version = self.ovs_properties.get('version', {}) ovs_ver = [int(x) for x in version.get('ovs', self.DEFAULT_OVS).split('.')] - ovs_add_port = \ - "ovs-vsctl add-port {br} {port} -- set Interface {port} type={type_}{dpdk_args}" - ovs_add_queue = "ovs-vsctl set Interface {port} options:n_rxq={queue}" - chmod_vpath = "chmod 0777 {0}/var/run/openvswitch/dpdkvhostuser*" - - cmd_dpdk_list = [ - "ovs-vsctl del-br br0", - "rm -rf {0}/var/run/openvswitch/dpdkvhostuser*".format(vpath), - "ovs-vsctl add-br br0 -- set bridge br0 datapath_type=netdev", + ovs_add_port = ('ovs-vsctl add-port {br} {port} -- ' + 'set Interface {port} type={type_}{dpdk_args}') + ovs_add_queue = 'ovs-vsctl set Interface {port} options:n_rxq={queue}' + chmod_vpath = 'chmod 0777 {0}/var/run/openvswitch/dpdkvhostuser*' + + cmd_list = [ + 'ovs-vsctl --if-exists del-br {0}'.format(MAIN_BRIDGE), + 'rm -rf {0}/var/run/openvswitch/dpdkvhostuser*'.format(vpath), + 'ovs-vsctl add-br {0} -- set bridge {0} datapath_type=netdev'. + format(MAIN_BRIDGE) ] - ordered_network = OrderedDict(self.networks) + ordered_network = collections.OrderedDict(self.networks) for index, vnf in enumerate(ordered_network.values()): if ovs_ver >= [2, 7, 0]: dpdk_args = " options:dpdk-devargs=%s" % vnf.get("phy_port") - dpdk_list.append(ovs_add_port.format(br='br0', port='dpdk%s' % vnf.get("port_num", 0), - type_='dpdk', dpdk_args=dpdk_args)) - dpdk_list.append(ovs_add_queue.format(port='dpdk%s' % vnf.get("port_num", 0), - queue=self.ovs_properties.get("queues", 1))) + dpdk_list.append(ovs_add_port.format( + br=MAIN_BRIDGE, port='dpdk%s' % vnf.get("port_num", 0), + type_='dpdk', dpdk_args=dpdk_args)) + dpdk_list.append(ovs_add_queue.format( + port='dpdk%s' % vnf.get("port_num", 0), + queue=self.ovs_properties.get("queues", 1))) # Sorting the array to make sure we execute dpdk0... in the order list.sort(dpdk_list) - cmd_dpdk_list.extend(dpdk_list) + cmd_list.extend(dpdk_list) # Need to do two for loop to maintain the dpdk/vhost ports. for index, _ in enumerate(ordered_network): - cmd_dpdk_list.append(ovs_add_port.format(br='br0', port='dpdkvhostuser%s' % index, - type_='dpdkvhostuser', dpdk_args="")) - - for cmd in cmd_dpdk_list: - LOG.info(cmd) - self.connection.execute(cmd) - - # Fixme: add flows code - ovs_flow = "ovs-ofctl add-flow br0 in_port=%s,action=output:%s" + cmd_list.append(ovs_add_port.format( + br=MAIN_BRIDGE, port='dpdkvhostuser%s' % index, + type_='dpdkvhostuser', dpdk_args="")) + ovs_flow = ("ovs-ofctl add-flow {0} in_port=%s,action=output:%s". + format(MAIN_BRIDGE)) network_count = len(ordered_network) + 1 for in_port, out_port in zip(range(1, network_count), range(network_count, network_count * 2)): - self.connection.execute(ovs_flow % (in_port, out_port)) - self.connection.execute(ovs_flow % (out_port, in_port)) + cmd_list.append(ovs_flow % (in_port, out_port)) + cmd_list.append(ovs_flow % (out_port, in_port)) - self.connection.execute(chmod_vpath.format(vpath)) + cmd_list.append(chmod_vpath.format(vpath)) + + for cmd in cmd_list: + LOG.info(cmd) + exit_status, _, stderr = self.connection.execute( + cmd, timeout=self.CMD_TIMEOUT) + if exit_status: + raise exceptions.OVSSetupError(command=cmd, error=stderr) + + def _check_hugepages(self): + meminfo = io.BytesIO() + self.connection.get_file_obj('/proc/meminfo', meminfo) + regex = re.compile(r"HugePages_Total:\s+(?P<hp_total>\d+)[\n\r]" + r"HugePages_Free:\s+(?P<hp_free>\d+)") + match = regex.search(meminfo.getvalue().decode('utf-8')) + if not match: + raise exceptions.OVSHugepagesInfoError() + if int(match.group('hp_total')) == 0: + raise exceptions.OVSHugepagesNotConfigured() + if int(match.group('hp_free')) == 0: + raise exceptions.OVSHugepagesZeroFree( + total_hugepages=int(match.group('hp_total'))) def cleanup_ovs_dpdk_env(self): - self.connection.execute("ovs-vsctl del-br br0") + self.connection.execute( + 'ovs-vsctl --if-exists del-br {0}'.format(MAIN_BRIDGE)) self.connection.execute("pkill -9 ovs") def check_ovs_dpdk_env(self): self.cleanup_ovs_dpdk_env() + self._check_hugepages() version = self.ovs_properties.get("version", {}) ovs_ver = version.get("ovs", self.DEFAULT_OVS) @@ -223,13 +243,15 @@ class OvsDpdkContext(Context): supported_version = self.SUPPORTED_OVS_TO_DPDK_MAP.get(ovs_ver, None) if supported_version is None or supported_version.split('.')[:2] != dpdk_ver[:2]: - raise Exception("Unsupported ovs '{}'. Please check the config...".format(ovs_ver)) + raise exceptions.OVSUnsupportedVersion( + ovs_version=ovs_ver, + ovs_to_dpdk_map=self.SUPPORTED_OVS_TO_DPDK_MAP) status = self.connection.execute("ovs-vsctl -V | grep -i '%s'" % ovs_ver)[0] if status: - deploy = OvsDeploy(self.connection, - get_nsb_option("bin_path"), - self.ovs_properties) + deploy = model.OvsDeploy(self.connection, + utils.get_nsb_option("bin_path"), + self.ovs_properties) deploy.ovs_deploy() def deploy(self): @@ -240,15 +262,12 @@ class OvsDpdkContext(Context): return self.connection = ssh.SSH.from_node(self.host_mgmt) - self.dpdk_devbind = provision_tool( - self.connection, - os.path.join(get_nsb_option("bin_path"), "dpdk-devbind.py")) # Check dpdk/ovs version, if not present install self.check_ovs_dpdk_env() # Todo: NFVi deploy (sriov, vswitch, ovs etc) based on the config. - StandaloneContextHelper.install_req_libs(self.connection) - self.networks = StandaloneContextHelper.get_nic_details( + model.StandaloneContextHelper.install_req_libs(self.connection) + self.networks = model.StandaloneContextHelper.get_nic_details( self.connection, self.networks, self.dpdk_devbind) self.setup_ovs() @@ -256,9 +275,8 @@ class OvsDpdkContext(Context): self.setup_ovs_bridge_add_flows() self.nodes = self.setup_ovs_dpdk_context() LOG.debug("Waiting for VM to come up...") - self.nodes = StandaloneContextHelper.wait_for_vnfs_to_start(self.connection, - self.servers, - self.nodes) + self.nodes = model.StandaloneContextHelper.wait_for_vnfs_to_start( + self.connection, self.servers, self.nodes) def undeploy(self): @@ -278,7 +296,7 @@ class OvsDpdkContext(Context): # Todo: NFVi undeploy (sriov, vswitch, ovs etc) based on the config. for vm in self.vm_names: - Libvirt.check_if_vm_exists_and_delete(vm, self.connection) + model.Libvirt.check_if_vm_exists_and_delete(vm, self.connection) def _get_server(self, attr_name): """lookup server info by name from context @@ -333,50 +351,53 @@ class OvsDpdkContext(Context): return result def configure_nics_for_ovs_dpdk(self): - portlist = OrderedDict(self.networks) + portlist = collections.OrderedDict(self.networks) for key in portlist: - mac = StandaloneContextHelper.get_mac_address() + mac = model.StandaloneContextHelper.get_mac_address() portlist[key].update({'mac': mac}) self.networks = portlist LOG.info("Ports %s", self.networks) - def _enable_interfaces(self, index, vfs, cfg): + def _enable_interfaces(self, index, vfs, xml_str): vpath = self.ovs_properties.get("vpath", "/usr/local") vf = self.networks[vfs[0]] port_num = vf.get('port_num', 0) - vpci = PciAddress(vf['vpci'].strip()) + vpci = utils.PciAddress(vf['vpci'].strip()) # Generate the vpci for the interfaces slot = index + port_num + 10 vf['vpci'] = \ "{}:{}:{:02x}.{}".format(vpci.domain, vpci.bus, slot, vpci.function) - Libvirt.add_ovs_interface(vpath, port_num, vf['vpci'], vf['mac'], str(cfg)) + return model.Libvirt.add_ovs_interface( + vpath, port_num, vf['vpci'], vf['mac'], xml_str) def setup_ovs_dpdk_context(self): nodes = [] self.configure_nics_for_ovs_dpdk() - for index, (key, vnf) in enumerate(OrderedDict(self.servers).items()): + for index, (key, vnf) in enumerate(collections.OrderedDict( + self.servers).items()): cfg = '/tmp/vm_ovs_%d.xml' % index vm_name = "vm_%d" % index # 1. Check and delete VM if already exists - Libvirt.check_if_vm_exists_and_delete(vm_name, self.connection) + model.Libvirt.check_if_vm_exists_and_delete(vm_name, + self.connection) + xml_str, mac = model.Libvirt.build_vm_xml( + self.connection, self.vm_flavor, vm_name, index) - _, mac = Libvirt.build_vm_xml(self.connection, self.vm_flavor, - cfg, vm_name, index) # 2: Cleanup already available VMs - for vkey, vfs in OrderedDict(vnf["network_ports"]).items(): - if vkey == "mgmt": - continue - self._enable_interfaces(index, vfs, cfg) + for vfs in [vfs for vfs_name, vfs in vnf["network_ports"].items() + if vfs_name != 'mgmt']: + xml_str = self._enable_interfaces(index, vfs, xml_str) # copy xml to target... + model.Libvirt.write_file(cfg, xml_str) self.connection.put(cfg, cfg) # NOTE: launch through libvirt LOG.info("virsh create ...") - Libvirt.virsh_create_vm(self.connection, cfg) + model.Libvirt.virsh_create_vm(self.connection, cfg) self.vm_names.append(vm_name) diff --git a/yardstick/benchmark/contexts/standalone/sriov.py b/yardstick/benchmark/contexts/standalone/sriov.py index d7620552b..95472fdda 100644 --- a/yardstick/benchmark/contexts/standalone/sriov.py +++ b/yardstick/benchmark/contexts/standalone/sriov.py @@ -16,15 +16,11 @@ from __future__ import absolute_import import os import logging import collections -from collections import OrderedDict from yardstick import ssh from yardstick.network_services.utils import get_nsb_option -from yardstick.network_services.utils import provision_tool from yardstick.benchmark.contexts.base import Context -from yardstick.benchmark.contexts.standalone.model import Libvirt -from yardstick.benchmark.contexts.standalone.model import StandaloneContextHelper -from yardstick.benchmark.contexts.standalone.model import Server +from yardstick.benchmark.contexts.standalone import model from yardstick.network_services.utils import PciAddress LOG = logging.getLogger(__name__) @@ -41,7 +37,8 @@ class SriovContext(Context): self.file_path = None self.sriov = [] self.first_run = True - self.dpdk_devbind = '' + self.dpdk_devbind = os.path.join(get_nsb_option('bin_path'), + 'dpdk-devbind.py') self.vm_names = [] self.nfvi_host = [] self.nodes = [] @@ -49,8 +46,8 @@ class SriovContext(Context): self.attrs = {} self.vm_flavor = None self.servers = None - self.helper = StandaloneContextHelper() - self.vnf_node = Server() + self.helper = model.StandaloneContextHelper() + self.vnf_node = model.Server() self.drivers = [] super(SriovContext, self).__init__() @@ -82,20 +79,16 @@ class SriovContext(Context): return self.connection = ssh.SSH.from_node(self.host_mgmt) - self.dpdk_devbind = provision_tool( - self.connection, - os.path.join(get_nsb_option("bin_path"), "dpdk-devbind.py")) # Todo: NFVi deploy (sriov, vswitch, ovs etc) based on the config. - StandaloneContextHelper.install_req_libs(self.connection) - self.networks = StandaloneContextHelper.get_nic_details( + model.StandaloneContextHelper.install_req_libs(self.connection) + self.networks = model.StandaloneContextHelper.get_nic_details( self.connection, self.networks, self.dpdk_devbind) self.nodes = self.setup_sriov_context() LOG.debug("Waiting for VM to come up...") - self.nodes = StandaloneContextHelper.wait_for_vnfs_to_start(self.connection, - self.servers, - self.nodes) + self.nodes = model.StandaloneContextHelper.wait_for_vnfs_to_start( + self.connection, self.servers, self.nodes) def undeploy(self): """don't need to undeploy""" @@ -105,7 +98,7 @@ class SriovContext(Context): # Todo: NFVi undeploy (sriov, vswitch, ovs etc) based on the config. for vm in self.vm_names: - Libvirt.check_if_vm_exists_and_delete(vm, self.connection) + model.Libvirt.check_if_vm_exists_and_delete(vm, self.connection) # Bind nics back to kernel for ports in self.networks.values(): @@ -136,8 +129,8 @@ class SriovContext(Context): except StopIteration: pass else: - raise ValueError("Duplicate nodes!!! Nodes: %s %s" % - (node, duplicate)) + raise ValueError("Duplicate nodes!!! Nodes: %s %s" + % (node, duplicate)) node["name"] = attr_name return node @@ -179,7 +172,7 @@ class SriovContext(Context): self.connection.execute(build_vfs.format(ports.get('phy_port'))) # configure VFs... - mac = StandaloneContextHelper.get_mac_address() + mac = model.StandaloneContextHelper.get_mac_address() interface = ports.get('interface') if interface is not None: self.connection.execute(vf_cmd.format(interface, mac)) @@ -201,7 +194,7 @@ class SriovContext(Context): slot = index + idx + 10 vf['vpci'] = \ "{}:{}:{:02x}.{}".format(vpci.domain, vpci.bus, slot, vpci.function) - Libvirt.add_sriov_interfaces( + model.Libvirt.add_sriov_interfaces( vf['vpci'], vf['vf_pci']['vf_pci'], vf['mac'], str(cfg)) self.connection.execute("ifconfig %s up" % vf['interface']) self.connection.execute(vf_spoofchk.format(vf['interface'])) @@ -212,34 +205,37 @@ class SriovContext(Context): # 1 : modprobe host_driver with num_vfs self.configure_nics_for_sriov() - for index, (key, vnf) in enumerate(OrderedDict(self.servers).items()): + for index, (key, vnf) in enumerate(collections.OrderedDict( + self.servers).items()): cfg = '/tmp/vm_sriov_%s.xml' % str(index) vm_name = "vm_%s" % str(index) # 1. Check and delete VM if already exists - Libvirt.check_if_vm_exists_and_delete(vm_name, self.connection) + model.Libvirt.check_if_vm_exists_and_delete(vm_name, + self.connection) + xml_str, mac = model.Libvirt.build_vm_xml( + self.connection, self.vm_flavor, vm_name, index) - _, mac = Libvirt.build_vm_xml(self.connection, self.vm_flavor, cfg, vm_name, index) # 2: Cleanup already available VMs - for idx, (vkey, vfs) in enumerate(OrderedDict(vnf["network_ports"]).items()): - if vkey == "mgmt": - continue + network_ports = collections.OrderedDict( + {k: v for k, v in vnf["network_ports"].items() if k != 'mgmt'}) + for idx, vfs in enumerate(network_ports.values()): self._enable_interfaces(index, idx, vfs, cfg) # copy xml to target... + model.Libvirt.write_file(cfg, xml_str) self.connection.put(cfg, cfg) # NOTE: launch through libvirt LOG.info("virsh create ...") - Libvirt.virsh_create_vm(self.connection, cfg) + model.Libvirt.virsh_create_vm(self.connection, cfg) self.vm_names.append(vm_name) # build vnf node details - nodes.append(self.vnf_node.generate_vnf_instance(self.vm_flavor, - self.networks, - self.host_mgmt.get('ip'), - key, vnf, mac)) + nodes.append(self.vnf_node.generate_vnf_instance( + self.vm_flavor, self.networks, self.host_mgmt.get('ip'), + key, vnf, mac)) return nodes @@ -248,7 +244,8 @@ class SriovContext(Context): "mac": vfmac, "pf_if": pfif } - vfs = StandaloneContextHelper.get_virtual_devices(self.connection, value) + vfs = model.StandaloneContextHelper.get_virtual_devices( + self.connection, value) for k, v in vfs.items(): m = PciAddress(k.strip()) m1 = PciAddress(value.strip()) diff --git a/yardstick/benchmark/core/task.py b/yardstick/benchmark/core/task.py index 4272a6db9..697cc007f 100644 --- a/yardstick/benchmark/core/task.py +++ b/yardstick/benchmark/core/task.py @@ -112,9 +112,9 @@ class Task(object): # pragma: no cover continue try: - data = self._run(tasks[i]['scenarios'], - tasks[i]['run_in_parallel'], - output_config) + success, data = self._run(tasks[i]['scenarios'], + tasks[i]['run_in_parallel'], + output_config) except KeyboardInterrupt: raise except Exception: # pylint: disable=broad-except @@ -123,9 +123,15 @@ class Task(object): # pragma: no cover testcases[tasks[i]['case_name']] = {'criteria': 'FAIL', 'tc_data': []} else: - LOG.info('Testcase: "%s" SUCCESS!!!', tasks[i]['case_name']) - testcases[tasks[i]['case_name']] = {'criteria': 'PASS', - 'tc_data': data} + if success: + LOG.info('Testcase: "%s" SUCCESS!!!', tasks[i]['case_name']) + testcases[tasks[i]['case_name']] = {'criteria': 'PASS', + 'tc_data': data} + else: + LOG.error('Testcase: "%s" FAILED!!!', tasks[i]['case_name'], + exc_info=True) + testcases[tasks[i]['case_name']] = {'criteria': 'FAIL', + 'tc_data': data} if args.keep_deploy: # keep deployment, forget about stack @@ -240,6 +246,7 @@ class Task(object): # pragma: no cover background_runners = [] + task_success = True result = [] # Start all background scenarios for scenario in filter(_is_background_scenario, scenarios): @@ -258,8 +265,8 @@ class Task(object): # pragma: no cover for runner in runners: status = runner_join(runner, background_runners, self.outputs, result) if status != 0: - raise RuntimeError( - "{0} runner status {1}".format(runner.__execution_type__, status)) + LOG.error("%s runner status %s", runner.__execution_type__, status) + task_success = False LOG.info("Runner ended") else: # run serially @@ -271,8 +278,8 @@ class Task(object): # pragma: no cover LOG.error('Scenario NO.%s: "%s" ERROR!', scenarios.index(scenario) + 1, scenario.get('type')) - raise RuntimeError( - "{0} runner status {1}".format(runner.__execution_type__, status)) + LOG.error("%s runner status %s", runner.__execution_type__, status) + task_success = False LOG.info("Runner ended") # Abort background runners @@ -289,7 +296,7 @@ class Task(object): # pragma: no cover base_runner.Runner.release(runner) print("Background task ended") - return result + return task_success, result def atexit_handler(self): """handler for process termination""" @@ -614,15 +621,25 @@ class TaskParser(object): # pragma: no cover vnf__0: vnf_0.yardstick """ def qualified_name(name): - node_name, context_name = name.split('.') + try: + # for openstack + node_name, context_name = name.split('.') + sep = '.' + except ValueError: + # for kubernetes, some kubernetes resources don't support + # name format like 'xxx.xxx', so we use '-' instead + # need unified later + node_name, context_name = name.split('-') + sep = '-' + try: ctx = next((context for context in contexts - if context.assigned_name == context_name)) + if context.assigned_name == context_name)) except StopIteration: raise y_exc.ScenarioConfigContextNameNotFound( context_name=context_name) - return '{}.{}'.format(node_name, ctx.name) + return '{}{}{}'.format(node_name, sep, ctx.name) if 'host' in scenario: scenario['host'] = qualified_name(scenario['host']) diff --git a/yardstick/benchmark/runners/base.py b/yardstick/benchmark/runners/base.py index 99386a440..fbdf6c281 100755 --- a/yardstick/benchmark/runners/base.py +++ b/yardstick/benchmark/runners/base.py @@ -121,7 +121,7 @@ class Runner(object): @staticmethod def terminate_all(): """Terminate all runners (subprocesses)""" - log.debug("Terminating all runners", exc_info=True) + log.debug("Terminating all runners") # release dumper process as some errors before any runner is created if not Runner.runners: diff --git a/yardstick/benchmark/runners/duration.py b/yardstick/benchmark/runners/duration.py index fbf72a74c..60b0348c3 100644 --- a/yardstick/benchmark/runners/duration.py +++ b/yardstick/benchmark/runners/duration.py @@ -66,6 +66,8 @@ def _worker_process(queue, cls, method_name, scenario_cfg, data = {} errors = "" + benchmark.pre_run_wait_time(interval) + try: result = method(data) except AssertionError as assertion: @@ -77,7 +79,7 @@ def _worker_process(queue, cls, method_name, scenario_cfg, errors = assertion.args # catch all exceptions because with multiprocessing we can have un-picklable exception # problems https://bugs.python.org/issue9400 - except Exception: + except Exception: # pylint: disable=broad-except errors = traceback.format_exc() LOG.exception("") else: @@ -86,7 +88,7 @@ def _worker_process(queue, cls, method_name, scenario_cfg, # if we do timeout we don't care about dropping individual KPIs output_queue.put(result, True, QUEUE_PUT_TIMEOUT) - time.sleep(interval) + benchmark.post_run_wait_time(interval) benchmark_output = { 'timestamp': time.time(), diff --git a/yardstick/benchmark/runners/iteration.py b/yardstick/benchmark/runners/iteration.py index cb0424377..20d6da054 100644 --- a/yardstick/benchmark/runners/iteration.py +++ b/yardstick/benchmark/runners/iteration.py @@ -71,6 +71,8 @@ def _worker_process(queue, cls, method_name, scenario_cfg, data = {} errors = "" + benchmark.pre_run_wait_time(interval) + try: result = method(data) except AssertionError as assertion: @@ -90,7 +92,7 @@ def _worker_process(queue, cls, method_name, scenario_cfg, scenario_cfg['options']['rate'] -= delta sequence = 1 continue - except Exception: + except Exception: # pylint: disable=broad-except errors = traceback.format_exc() LOG.exception("") else: @@ -99,7 +101,7 @@ def _worker_process(queue, cls, method_name, scenario_cfg, # if we do timeout we don't care about dropping individual KPIs output_queue.put(result, True, QUEUE_PUT_TIMEOUT) - time.sleep(interval) + benchmark.post_run_wait_time(interval) benchmark_output = { 'timestamp': time.time(), diff --git a/yardstick/benchmark/scenarios/availability/scenario_general.py b/yardstick/benchmark/scenarios/availability/scenario_general.py index 9ac55471d..1fadd2532 100644 --- a/yardstick/benchmark/scenarios/availability/scenario_general.py +++ b/yardstick/benchmark/scenarios/availability/scenario_general.py @@ -26,7 +26,6 @@ class ScenarioGeneral(base.Scenario): self.scenario_cfg = scenario_cfg self.context_cfg = context_cfg self.intermediate_variables = {} - self.pass_flag = True def setup(self): self.director = Director(self.scenario_cfg, self.context_cfg) @@ -47,7 +46,7 @@ class ScenarioGeneral(base.Scenario): step['actionType'], step['actionKey']) if actionRollbacker: self.director.executionSteps.append(actionRollbacker) - except Exception: + except Exception: # pylint: disable=broad-except LOG.exception("Exception") LOG.debug( "\033[91m exception when running step: %s .... \033[0m", @@ -59,31 +58,16 @@ class ScenarioGeneral(base.Scenario): self.director.stopMonitors() verify_result = self.director.verify() - - self.director.store_result(result) - for k, v in self.director.data.items(): if v == 0: result['sla_pass'] = 0 verify_result = False - self.pass_flag = False - LOG.info( - "\033[92m The service process not found in the host \ -envrioment, the HA test case NOT pass") + LOG.info("\033[92m The service process (%s) not found in the host environment", k) - if verify_result: - result['sla_pass'] = 1 - LOG.info( - "\033[92m Congratulations, " - "the HA test case PASS! \033[0m") - else: - result['sla_pass'] = 0 - self.pass_flag = False - LOG.info( - "\033[91m Aoh, the HA test case FAIL," - "please check the detail debug information! \033[0m") + result['sla_pass'] = 1 if verify_result else 0 + self.director.store_result(result) + + assert verify_result is True, "The HA test case NOT passed" def teardown(self): self.director.knockoff() - - assert self.pass_flag, "The HA test case NOT passed" diff --git a/yardstick/benchmark/scenarios/availability/serviceha.py b/yardstick/benchmark/scenarios/availability/serviceha.py index 6d0d812af..dcd0fe598 100755 --- a/yardstick/benchmark/scenarios/availability/serviceha.py +++ b/yardstick/benchmark/scenarios/availability/serviceha.py @@ -29,7 +29,6 @@ class ServiceHA(base.Scenario): self.context_cfg = context_cfg self.setup_done = False self.data = {} - self.pass_flag = True def setup(self): """scenario setup""" @@ -73,18 +72,12 @@ class ServiceHA(base.Scenario): sla_pass = self.monitorMgr.verify_SLA() for k, v in self.data.items(): if v == 0: - result['sla_pass'] = 0 - self.pass_flag = False - LOG.info("The service process not found in the host envrioment, \ -the HA test case NOT pass") - return + sla_pass = False + LOG.info("The service process (%s) not found in the host envrioment", k) + + result['sla_pass'] = 1 if sla_pass else 0 self.monitorMgr.store_result(result) - if sla_pass: - result['sla_pass'] = 1 - LOG.info("The HA test case PASS the SLA") - else: - result['sla_pass'] = 0 - self.pass_flag = False + assert sla_pass is True, "The HA test case NOT pass the SLA" return @@ -94,8 +87,6 @@ the HA test case NOT pass") for attacker in self.attackers: attacker.recover() - assert self.pass_flag, "The HA test case NOT passed" - def _test(): # pragma: no cover """internal test function""" diff --git a/yardstick/benchmark/scenarios/base.py b/yardstick/benchmark/scenarios/base.py index 10a728828..58a02805c 100644 --- a/yardstick/benchmark/scenarios/base.py +++ b/yardstick/benchmark/scenarios/base.py @@ -13,9 +13,10 @@ # License for the specific language governing permissions and limitations # under the License. -# yardstick comment: this is a modified copy of -# rally/rally/benchmark/scenarios/base.py +import abc +import time +import six from stevedore import extension import yardstick.common.utils as utils @@ -37,20 +38,29 @@ def _iter_scenario_classes(scenario_type=None): yield scenario +@six.add_metaclass(abc.ABCMeta) class Scenario(object): def setup(self): - """ default impl for scenario setup """ + """Default setup implementation for Scenario classes""" pass + @abc.abstractmethod def run(self, *args): - """ catcher for not implemented run methods in subclasses """ - raise RuntimeError("run method not implemented") + """Entry point for scenario classes, called from runner worker""" def teardown(self): - """ default impl for scenario teardown """ + """Default teardown implementation for Scenario classes""" pass + def pre_run_wait_time(self, time_seconds): + """Time waited before executing the run method""" + pass + + def post_run_wait_time(self, time_seconds): + """Time waited after executing the run method""" + time.sleep(time_seconds) + @staticmethod def get_types(): """return a list of known runner type (class) names""" @@ -88,10 +98,14 @@ class Scenario(object): """ return cls.__doc__.splitlines()[0] if cls.__doc__ else str(None) - def _push_to_outputs(self, keys, values): + @staticmethod + def _push_to_outputs(keys, values): + """Return a dictionary given the keys and the values""" return dict(zip(keys, values)) - def _change_obj_to_dict(self, obj): + @staticmethod + def _change_obj_to_dict(obj): + """Return a dictionary from the __dict__ attribute of an object""" dic = {} for k, v in vars(obj).items(): try: diff --git a/yardstick/benchmark/scenarios/compute/unixbench_benchmark.bash b/yardstick/benchmark/scenarios/compute/unixbench_benchmark.bash index 5a5dbc394..9f1804819 100644 --- a/yardstick/benchmark/scenarios/compute/unixbench_benchmark.bash +++ b/yardstick/benchmark/scenarios/compute/unixbench_benchmark.bash @@ -18,7 +18,7 @@ OUTPUT_FILE=/tmp/unixbench-out.log # run unixbench test run_unixbench() { - cd /opt/tempT/UnixBench/ + cd /opt/tempT/UnixBench/UnixBench/ ./Run $OPTIONS > $OUTPUT_FILE } diff --git a/yardstick/benchmark/scenarios/lib/attach_volume.py b/yardstick/benchmark/scenarios/lib/attach_volume.py index 88124964b..96dd130b1 100644 --- a/yardstick/benchmark/scenarios/lib/attach_volume.py +++ b/yardstick/benchmark/scenarios/lib/attach_volume.py @@ -6,30 +6,31 @@ # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 ############################################################################## - -from __future__ import print_function -from __future__ import absolute_import - import logging from yardstick.benchmark.scenarios import base -import yardstick.common.openstack_utils as op_utils +from yardstick.common import openstack_utils +from yardstick.common import exceptions LOG = logging.getLogger(__name__) class AttachVolume(base.Scenario): - """Attach a volmeu to an instance""" + """Attach a volume to an instance""" __scenario_type__ = "AttachVolume" def __init__(self, scenario_cfg, context_cfg): self.scenario_cfg = scenario_cfg self.context_cfg = context_cfg - self.options = self.scenario_cfg['options'] + self.options = self.scenario_cfg["options"] - self.server_id = self.options.get("server_id", "TestServer") - self.volume_id = self.options.get("volume_id", None) + self.server_name_or_id = self.options["server_name_or_id"] + self.volume_name_or_id = self.options["volume_name_or_id"] + self.device = self.options.get("device") + self.wait = self.options.get("wait", True) + self.timeout = self.options.get("timeout") + self.shade_client = openstack_utils.get_shade_client() self.setup_done = False @@ -44,10 +45,14 @@ class AttachVolume(base.Scenario): if not self.setup_done: self.setup() - status = op_utils.attach_server_volume(self.server_id, - self.volume_id) + status = openstack_utils.attach_volume_to_server( + self.shade_client, self.server_name_or_id, self.volume_name_or_id, + device=self.device, wait=self.wait, timeout=self.timeout) + + if not status: + result.update({"attach_volume": 0}) + LOG.error("Attach volume to server failed!") + raise exceptions.ScenarioAttachVolumeError - if status: - LOG.info("Attach volume to server successful!") - else: - LOG.info("Attach volume to server failed!") + result.update({"attach_volume": 1}) + LOG.info("Attach volume to server successful!") diff --git a/yardstick/benchmark/scenarios/lib/create_floating_ip.py b/yardstick/benchmark/scenarios/lib/create_floating_ip.py index 7108722af..e29f9d1fc 100644 --- a/yardstick/benchmark/scenarios/lib/create_floating_ip.py +++ b/yardstick/benchmark/scenarios/lib/create_floating_ip.py @@ -11,7 +11,8 @@ import logging import os from yardstick.benchmark.scenarios import base -import yardstick.common.openstack_utils as op_utils +from yardstick.common import openstack_utils +from yardstick.common import exceptions LOG = logging.getLogger(__name__) @@ -26,9 +27,18 @@ class CreateFloatingIp(base.Scenario): self.scenario_cfg = scenario_cfg self.context_cfg = context_cfg self.ext_net_id = os.getenv("EXTERNAL_NETWORK", "external") + self.options = self.scenario_cfg["options"] + + self.network_name_or_id = self.options.get("network_name_or_id", self.ext_net_id) + self.server = self.options.get("server") + self.fixed_address = self.options.get("fixed_address") + self.nat_destination = self.options.get("nat_destination") + self.port = self.options.get("port") + self.wait = self.options.get("wait", False) + self.timeout = self.options.get("timeout", 60) + + self.shade_client = openstack_utils.get_shade_client() - self.neutron_client = op_utils.get_neutron_client() - self.shade_client = op_utils.get_shade_client() self.setup_done = False def setup(self): @@ -36,21 +46,25 @@ class CreateFloatingIp(base.Scenario): self.setup_done = True - def run(self, *args): + def run(self, result): """execute the test""" if not self.setup_done: self.setup() - net_id = op_utils.get_network_id(self.shade_client, self.ext_net_id) - floating_info = op_utils.create_floating_ip(self.neutron_client, - extnet_id=net_id) + floating_info = openstack_utils.create_floating_ip( + self.shade_client, network_name_or_id=self.network_name_or_id, + server=self.server, fixed_address=self.fixed_address, + nat_destination=self.nat_destination, port=self.port, + wait=self.wait, timeout=self.timeout) if not floating_info: + result.update({"floating_ip_create": 0}) LOG.error("Creating floating ip failed!") - return + raise exceptions.ScenarioCreateFloatingIPError + result.update({"floating_ip_create": 1}) LOG.info("Creating floating ip successful!") - keys = self.scenario_cfg.get('output', '').split() + keys = self.scenario_cfg.get("output", '').split() values = [floating_info["fip_id"], floating_info["fip_addr"]] return self._push_to_outputs(keys, values) diff --git a/yardstick/benchmark/scenarios/lib/create_keypair.py b/yardstick/benchmark/scenarios/lib/create_keypair.py index f5b1fff7a..ee9bc440a 100644 --- a/yardstick/benchmark/scenarios/lib/create_keypair.py +++ b/yardstick/benchmark/scenarios/lib/create_keypair.py @@ -6,15 +6,11 @@ # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 ############################################################################## - -from __future__ import print_function -from __future__ import absolute_import - import logging -import paramiko from yardstick.benchmark.scenarios import base -import yardstick.common.openstack_utils as op_utils +from yardstick.common import openstack_utils +from yardstick.common import exceptions LOG = logging.getLogger(__name__) @@ -27,10 +23,11 @@ class CreateKeypair(base.Scenario): def __init__(self, scenario_cfg, context_cfg): self.scenario_cfg = scenario_cfg self.context_cfg = context_cfg - self.options = self.scenario_cfg['options'] + self.options = self.scenario_cfg["options"] - self.key_name = self.options.get("key_name", "yardstick_key") - self.key_filename = self.options.get("key_path", "/tmp/yardstick_key") + self.name = self.options["key_name"] + self.public_key = self.options.get("public_key") + self.shade_client = openstack_utils.get_shade_client() self.setup_done = False @@ -45,27 +42,17 @@ class CreateKeypair(base.Scenario): if not self.setup_done: self.setup() - rsa_key = paramiko.RSAKey.generate(bits=2048, progress_func=None) - rsa_key.write_private_key_file(self.key_filename) - LOG.info("Writing key_file %s ...", self.key_filename) - with open(self.key_filename + ".pub", "w") as pubkey_file: - pubkey_file.write( - "%s %s\n" % (rsa_key.get_name(), rsa_key.get_base64())) - del rsa_key - - keypair = op_utils.create_keypair(self.key_name, - self.key_filename + ".pub") + keypair = openstack_utils.create_keypair( + self.shade_client, self.name, public_key=self.public_key) - if keypair: - result.update({"keypair_create": 1}) - LOG.info("Create keypair successful!") - else: + if not keypair: result.update({"keypair_create": 0}) - LOG.info("Create keypair failed!") - try: - keys = self.scenario_cfg.get('output', '').split() - except KeyError: - pass - else: - values = [keypair.id] - return self._push_to_outputs(keys, values) + LOG.error("Create keypair failed!") + raise exceptions.ScenarioCreateKeypairError + + result.update({"keypair_create": 1}) + LOG.info("Create keypair successful!") + keys = self.scenario_cfg.get("output", '').split() + keypair_id = keypair["id"] + values = [keypair_id] + return self._push_to_outputs(keys, values) diff --git a/yardstick/benchmark/scenarios/lib/create_sec_group.py b/yardstick/benchmark/scenarios/lib/create_sec_group.py index 3d1aec9e8..1d2e36488 100644 --- a/yardstick/benchmark/scenarios/lib/create_sec_group.py +++ b/yardstick/benchmark/scenarios/lib/create_sec_group.py @@ -7,13 +7,11 @@ # http://www.apache.org/licenses/LICENSE-2.0 ############################################################################## -from __future__ import print_function -from __future__ import absolute_import - import logging from yardstick.benchmark.scenarios import base -import yardstick.common.openstack_utils as op_utils +from yardstick.common import openstack_utils +from yardstick.common import exceptions LOG = logging.getLogger(__name__) @@ -26,11 +24,12 @@ class CreateSecgroup(base.Scenario): def __init__(self, scenario_cfg, context_cfg): self.scenario_cfg = scenario_cfg self.context_cfg = context_cfg - self.options = self.scenario_cfg['options'] + self.options = self.scenario_cfg["options"] - self.sg_name = self.options.get("sg_name", "yardstick_sec_group") - self.description = self.options.get("description", None) - self.neutron_client = op_utils.get_neutron_client() + self.sg_name = self.options["sg_name"] + self.description = self.options.get("description", "") + self.project_id = self.options.get("project_id") + self.shade_client = openstack_utils.get_shade_client() self.setup_done = False @@ -45,21 +44,16 @@ class CreateSecgroup(base.Scenario): if not self.setup_done: self.setup() - sg_id = op_utils.create_security_group_full(self.neutron_client, - sg_name=self.sg_name, - sg_description=self.description) - - if sg_id: - result.update({"sg_create": 1}) - LOG.info("Create security group successful!") - else: + sg_id = openstack_utils.create_security_group_full( + self.shade_client, self.sg_name, sg_description=self.description, + project_id=self.project_id) + if not sg_id: result.update({"sg_create": 0}) LOG.error("Create security group failed!") + raise exceptions.ScenarioCreateSecurityGroupError - try: - keys = self.scenario_cfg.get('output', '').split() - except KeyError: - pass - else: - values = [sg_id] - return self._push_to_outputs(keys, values) + result.update({"sg_create": 1}) + LOG.info("Create security group successful!") + keys = self.scenario_cfg.get("output", '').split() + values = [sg_id] + return self._push_to_outputs(keys, values) diff --git a/yardstick/benchmark/scenarios/lib/create_server.py b/yardstick/benchmark/scenarios/lib/create_server.py index 31ba18ed4..e2748aecf 100644 --- a/yardstick/benchmark/scenarios/lib/create_server.py +++ b/yardstick/benchmark/scenarios/lib/create_server.py @@ -6,14 +6,11 @@ # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 ############################################################################## - -from __future__ import print_function -from __future__ import absolute_import - import logging from yardstick.benchmark.scenarios import base -import yardstick.common.openstack_utils as op_utils +from yardstick.common import openstack_utils +from yardstick.common import exceptions LOG = logging.getLogger(__name__) @@ -26,15 +23,27 @@ class CreateServer(base.Scenario): def __init__(self, scenario_cfg, context_cfg): self.scenario_cfg = scenario_cfg self.context_cfg = context_cfg - self.options = self.scenario_cfg['options'] - - self.image_name = self.options.get("image_name", None) - self.flavor_name = self.options.get("flavor_name", None) - self.openstack = self.options.get("openstack_paras", None) - - self.glance_client = op_utils.get_glance_client() - self.neutron_client = op_utils.get_neutron_client() - self.nova_client = op_utils.get_nova_client() + self.options = self.scenario_cfg["options"] + + self.name = self.options["name"] + self.image = self.options["image"] + self.flavor = self.options["flavor"] + self.auto_ip = self.options.get("auto_ip", True) + self.ips = self.options.get("ips") + self.ip_pool = self.options.get("ip_pool") + self.root_volume = self.options.get("root_volume") + self.terminate_volume = self.options.get("terminate_volume", False) + self.wait = self.options.get("wait", True) + self.timeout = self.options.get("timeout", 180) + self.reuse_ips = self.options.get("reuse_ips", True) + self.network = self.options.get("network") + self.boot_from_volume = self.options.get("boot_from_volume", False) + self.volume_size = self.options.get("volume_size", "20") + self.boot_volume = self.options.get("boot_volume") + self.volumes = self.options.get("volumes") + self.nat_destination = self.options.get("nat_destination") + + self.shade_client = openstack_utils.get_shade_client() self.setup_done = False @@ -49,26 +58,23 @@ class CreateServer(base.Scenario): if not self.setup_done: self.setup() - if self.image_name is not None: - self.openstack['image'] = op_utils.get_image_id(self.glance_client, - self.image_name) - if self.flavor_name is not None: - self.openstack['flavor'] = op_utils.get_flavor_id(self.nova_client, - self.flavor_name) - - vm = op_utils.create_instance_and_wait_for_active(self.openstack) - - if vm: - result.update({"instance_create": 1}) - LOG.info("Create server successful!") - else: + server = openstack_utils.create_instance_and_wait_for_active( + self.shade_client, self.name, self.image, + self.flavor, auto_ip=self.auto_ip, ips=self.ips, + ip_pool=self.ip_pool, root_volume=self.root_volume, + terminate_volume=self.terminate_volume, wait=self.wait, + timeout=self.timeout, reuse_ips=self.reuse_ips, + network=self.network, boot_from_volume=self.boot_from_volume, + volume_size=self.volume_size, boot_volume=self.boot_volume, + volumes=self.volumes, nat_destination=self.nat_destination) + + if not server: result.update({"instance_create": 0}) LOG.error("Create server failed!") + raise exceptions.ScenarioCreateServerError - try: - keys = self.scenario_cfg.get('output', '').split() - except KeyError: - pass - else: - values = [vm.id] - return self._push_to_outputs(keys, values) + result.update({"instance_create": 1}) + LOG.info("Create instance successful!") + keys = self.scenario_cfg.get("output", '').split() + values = [server["id"]] + return self._push_to_outputs(keys, values) diff --git a/yardstick/benchmark/scenarios/lib/delete_floating_ip.py b/yardstick/benchmark/scenarios/lib/delete_floating_ip.py index 4314952fb..a35445f6f 100644 --- a/yardstick/benchmark/scenarios/lib/delete_floating_ip.py +++ b/yardstick/benchmark/scenarios/lib/delete_floating_ip.py @@ -7,13 +7,12 @@ # http://www.apache.org/licenses/LICENSE-2.0 ############################################################################## -from __future__ import print_function -from __future__ import absolute_import - import logging +from yardstick.common import openstack_utils +from yardstick.common import exceptions from yardstick.benchmark.scenarios import base -import yardstick.common.openstack_utils as op_utils + LOG = logging.getLogger(__name__) @@ -28,9 +27,10 @@ class DeleteFloatingIp(base.Scenario): self.context_cfg = context_cfg self.options = self.scenario_cfg['options'] - self.floating_ip_id = self.options.get("floating_ip_id", None) + self.floating_ip_id = self.options["floating_ip_id"] + self.retry = self.options.get("retry", 1) - self.nova_client = op_utils.get_nova_client() + self.shade_client = openstack_utils.get_shade_client() self.setup_done = False def setup(self): @@ -44,11 +44,13 @@ class DeleteFloatingIp(base.Scenario): if not self.setup_done: self.setup() - status = op_utils.delete_floating_ip(nova_client=self.nova_client, - floatingip_id=self.floating_ip_id) - if status: - result.update({"delete_floating_ip": 1}) - LOG.info("Delete floating ip successful!") - else: + status = openstack_utils.delete_floating_ip( + self.shade_client, self.floating_ip_id, + retry=self.retry) + if not status: result.update({"delete_floating_ip": 0}) LOG.error("Delete floating ip failed!") + raise exceptions.ScenarioDeleteFloatingIPError + + result.update({"delete_floating_ip": 1}) + LOG.info("Delete floating ip successful!") diff --git a/yardstick/benchmark/scenarios/lib/delete_keypair.py b/yardstick/benchmark/scenarios/lib/delete_keypair.py index 135139959..a52a38567 100644 --- a/yardstick/benchmark/scenarios/lib/delete_keypair.py +++ b/yardstick/benchmark/scenarios/lib/delete_keypair.py @@ -6,14 +6,12 @@ # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 ############################################################################## - -from __future__ import print_function -from __future__ import absolute_import - import logging +from yardstick.common import openstack_utils +from yardstick.common import exceptions from yardstick.benchmark.scenarios import base -import yardstick.common.openstack_utils as op_utils + LOG = logging.getLogger(__name__) @@ -26,11 +24,11 @@ class DeleteKeypair(base.Scenario): def __init__(self, scenario_cfg, context_cfg): self.scenario_cfg = scenario_cfg self.context_cfg = context_cfg - self.options = self.scenario_cfg['options'] + self.options = self.scenario_cfg["options"] - self.key_name = self.options.get("key_name", "yardstick_key") + self.key_name = self.options["key_name"] - self.nova_client = op_utils.get_nova_client() + self.shade_client = openstack_utils.get_shade_client() self.setup_done = False @@ -45,12 +43,13 @@ class DeleteKeypair(base.Scenario): if not self.setup_done: self.setup() - status = op_utils.delete_keypair(self.nova_client, - self.key_name) + status = openstack_utils.delete_keypair(self.shade_client, + self.key_name) - if status: - result.update({"delete_keypair": 1}) - LOG.info("Delete keypair successful!") - else: + if not status: result.update({"delete_keypair": 0}) - LOG.info("Delete keypair failed!") + LOG.error("Delete keypair failed!") + raise exceptions.ScenarioDeleteKeypairError + + result.update({"delete_keypair": 1}) + LOG.info("Delete keypair successful!") diff --git a/yardstick/benchmark/scenarios/lib/delete_network.py b/yardstick/benchmark/scenarios/lib/delete_network.py index 2e8b595f9..8874e8b1e 100644 --- a/yardstick/benchmark/scenarios/lib/delete_network.py +++ b/yardstick/benchmark/scenarios/lib/delete_network.py @@ -10,7 +10,8 @@ import logging from yardstick.benchmark.scenarios import base -import yardstick.common.openstack_utils as op_utils +from yardstick.common import openstack_utils +from yardstick.common import exceptions LOG = logging.getLogger(__name__) @@ -24,11 +25,11 @@ class DeleteNetwork(base.Scenario): def __init__(self, scenario_cfg, context_cfg): self.scenario_cfg = scenario_cfg self.context_cfg = context_cfg - self.options = self.scenario_cfg['options'] + self.options = self.scenario_cfg["options"] - self.network_id = self.options.get("network_id", None) + self.network_name_or_id = self.options["network_name_or_id"] - self.shade_client = op_utils.get_shade_client() + self.shade_client = openstack_utils.get_shade_client() self.setup_done = False @@ -43,12 +44,13 @@ class DeleteNetwork(base.Scenario): if not self.setup_done: self.setup() - status = op_utils.delete_neutron_net(self.shade_client, - network_id=self.network_id) - if status: - result.update({"delete_network": 1}) - LOG.info("Delete network successful!") - else: + status = openstack_utils.delete_neutron_net(self.shade_client, + self.network_name_or_id) + + if not status: result.update({"delete_network": 0}) LOG.error("Delete network failed!") - return status + raise exceptions.ScenarioDeleteNetworkError + + result.update({"delete_network": 1}) + LOG.info("Delete network successful!") diff --git a/yardstick/benchmark/scenarios/lib/delete_router_interface.py b/yardstick/benchmark/scenarios/lib/delete_router_interface.py index 117c80811..e71aed3ef 100644 --- a/yardstick/benchmark/scenarios/lib/delete_router_interface.py +++ b/yardstick/benchmark/scenarios/lib/delete_router_interface.py @@ -7,13 +7,11 @@ # http://www.apache.org/licenses/LICENSE-2.0 ############################################################################## -from __future__ import print_function -from __future__ import absolute_import - import logging from yardstick.benchmark.scenarios import base -import yardstick.common.openstack_utils as op_utils +from yardstick.common import openstack_utils +from yardstick.common import exceptions LOG = logging.getLogger(__name__) @@ -28,10 +26,11 @@ class DeleteRouterInterface(base.Scenario): self.context_cfg = context_cfg self.options = self.scenario_cfg['options'] - self.subnet_id = self.options.get("subnet_id", None) - self.router_id = self.options.get("router_id", None) + self.router = self.options["router"] + self.subnet_id = self.options.get("subnet_id") + self.port_id = self.options.get("port_id") - self.neutron_client = op_utils.get_neutron_client() + self.shade_client = openstack_utils.get_shade_client() self.setup_done = False @@ -46,12 +45,13 @@ class DeleteRouterInterface(base.Scenario): if not self.setup_done: self.setup() - status = op_utils.remove_interface_router(self.neutron_client, - router_id=self.router_id, - subnet_id=self.subnet_id) - if status: - result.update({"delete_router_interface": 1}) - LOG.info("Delete router interface successful!") - else: + status = openstack_utils.remove_router_interface( + self.shade_client, self.router, subnet_id=self.subnet_id, + port_id=self.port_id) + if not status: result.update({"delete_router_interface": 0}) LOG.error("Delete router interface failed!") + raise exceptions.ScenarioRemoveRouterIntError + + result.update({"delete_router_interface": 1}) + LOG.info("Delete router interface successful!") diff --git a/yardstick/benchmark/scenarios/lib/delete_server.py b/yardstick/benchmark/scenarios/lib/delete_server.py index bcd8faba7..46229ff04 100644 --- a/yardstick/benchmark/scenarios/lib/delete_server.py +++ b/yardstick/benchmark/scenarios/lib/delete_server.py @@ -6,14 +6,11 @@ # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 ############################################################################## - -from __future__ import print_function -from __future__ import absolute_import - import logging +from yardstick.common import openstack_utils +from yardstick.common import exceptions from yardstick.benchmark.scenarios import base -import yardstick.common.openstack_utils as op_utils LOG = logging.getLogger(__name__) @@ -26,9 +23,13 @@ class DeleteServer(base.Scenario): def __init__(self, scenario_cfg, context_cfg): self.scenario_cfg = scenario_cfg self.context_cfg = context_cfg - self.options = self.scenario_cfg['options'] - self.server_id = self.options.get("server_id", None) - self.nova_client = op_utils.get_nova_client() + self.options = self.scenario_cfg["options"] + self.server_name_or_id = self.options["name_or_id"] + self.wait = self.options.get("wait", False) + self.timeout = self.options.get("timeout", 180) + self.delete_ips = self.options.get("delete_ips", False) + self.delete_ip_retry = self.options.get("delete_ip_retry", 1) + self.shade_client = openstack_utils.get_shade_client() self.setup_done = False @@ -43,9 +44,15 @@ class DeleteServer(base.Scenario): if not self.setup_done: self.setup() - status = op_utils.delete_instance(self.nova_client, - instance_id=self.server_id) - if status: - LOG.info("Delete server successful!") - else: + status = openstack_utils.delete_instance( + self.shade_client, self.server_name_or_id, wait=self.wait, + timeout=self.timeout, delete_ips=self.delete_ips, + delete_ip_retry=self.delete_ip_retry) + + if not status: + result.update({"delete_server": 0}) LOG.error("Delete server failed!") + raise exceptions.ScenarioDeleteServerError + + result.update({"delete_server": 1}) + LOG.info("Delete server successful!") diff --git a/yardstick/benchmark/scenarios/lib/get_flavor.py b/yardstick/benchmark/scenarios/lib/get_flavor.py index d5e33947e..6727a7343 100644 --- a/yardstick/benchmark/scenarios/lib/get_flavor.py +++ b/yardstick/benchmark/scenarios/lib/get_flavor.py @@ -6,14 +6,11 @@ # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 ############################################################################## - -from __future__ import print_function -from __future__ import absolute_import - import logging from yardstick.benchmark.scenarios import base -import yardstick.common.openstack_utils as op_utils +from yardstick.common import openstack_utils +from yardstick.common import exceptions LOG = logging.getLogger(__name__) @@ -26,8 +23,12 @@ class GetFlavor(base.Scenario): def __init__(self, scenario_cfg, context_cfg): self.scenario_cfg = scenario_cfg self.context_cfg = context_cfg - self.options = self.scenario_cfg['options'] - self.flavor_name = self.options.get("flavor_name", "TestFlavor") + self.options = self.scenario_cfg["options"] + self.name_or_id = self.options["name_or_id"] + self.filters = self.options.get("filters") + self.get_extra = self.options.get("get_extra", True) + self.shade_client = openstack_utils.get_shade_client() + self.setup_done = False def setup(self): @@ -41,14 +42,18 @@ class GetFlavor(base.Scenario): if not self.setup_done: self.setup() - LOG.info("Querying flavor: %s", self.flavor_name) - flavor = op_utils.get_flavor_by_name(self.flavor_name) - if flavor: - LOG.info("Get flavor successful!") - values = [self._change_obj_to_dict(flavor)] - else: - LOG.info("Get flavor: no flavor matched!") - values = [] + LOG.info("Querying flavor: %s", self.name_or_id) + flavor = openstack_utils.get_flavor( + self.shade_client, self.name_or_id, filters=self.filters, + get_extra=self.get_extra) + + if not flavor: + result.update({"get_flavor": 0}) + LOG.error("Get flavor failed!") + raise exceptions.ScenarioGetFlavorError - keys = self.scenario_cfg.get('output', '').split() + result.update({"get_flavor": 1}) + LOG.info("Get flavor successful!") + values = [flavor] + keys = self.scenario_cfg.get("output", '').split() return self._push_to_outputs(keys, values) diff --git a/yardstick/benchmark/scenarios/lib/get_server.py b/yardstick/benchmark/scenarios/lib/get_server.py index fcf47c80d..f65fa9ebf 100644 --- a/yardstick/benchmark/scenarios/lib/get_server.py +++ b/yardstick/benchmark/scenarios/lib/get_server.py @@ -6,14 +6,11 @@ # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 ############################################################################## - -from __future__ import print_function -from __future__ import absolute_import - import logging from yardstick.benchmark.scenarios import base -import yardstick.common.openstack_utils as op_utils +from yardstick.common import openstack_utils +from yardstick.common import exceptions LOG = logging.getLogger(__name__) @@ -21,63 +18,58 @@ LOG = logging.getLogger(__name__) class GetServer(base.Scenario): """Get a server instance - Parameters - server_id - ID of the server - type: string - unit: N/A - default: null - server_name - name of the server - type: string - unit: N/A - default: null - - Either server_id or server_name is required. - - Outputs + Parameters: + name_or_id - Name or ID of the server + type: string + filters - meta data to use for further filtering + type: dict + detailed: Whether or not to add detailed additional information. + type: bool + bare: Whether to skip adding any additional information to the server + record. + type: bool + all_projects: Whether to get server from all projects or just the current + auth scoped project. + type: bool + + Outputs: rc - response code of getting server instance - 0 for success - 1 for failure + 1 for success + 0 for failure type: int - unit: N/A server - instance of the server type: dict - unit: N/A + """ - __scenario_type__ = "GetServer" + __scenario_type__ = 'GetServer' def __init__(self, scenario_cfg, context_cfg): self.scenario_cfg = scenario_cfg self.context_cfg = context_cfg - self.options = self.scenario_cfg.get('options', {}) + self.options = self.scenario_cfg['options'] - self.server_id = self.options.get("server_id") - if self.server_id: - LOG.debug('Server id is %s', self.server_id) + self.server_name_or_id = self.options.get('name_or_id') + self.filters = self.options.get('filters') + self.detailed = self.options.get('detailed', False) + self.bare = self.options.get('bare', False) - default_name = self.scenario_cfg.get('host', - self.scenario_cfg.get('target')) - self.server_name = self.options.get('server_name', default_name) - if self.server_name: - LOG.debug('Server name is %s', self.server_name) - - self.nova_client = op_utils.get_nova_client() + self.shade_client = openstack_utils.get_shade_client() def run(self, result): """execute the test""" - if self.server_id: - server = self.nova_client.servers.get(self.server_id) - else: - server = op_utils.get_server_by_name(self.server_name) - - keys = self.scenario_cfg.get('output', '').split() + server = openstack_utils.get_server( + self.shade_client, name_or_id=self.server_name_or_id, + filters=self.filters, detailed=self.detailed, bare=self.bare) - if server: - LOG.info("Get server successful!") - values = [0, self._change_obj_to_dict(server)] - else: - LOG.info("Get server failed!") - values = [1] + if not server: + result.update({'get_server': 0}) + LOG.error('Get Server failed!') + raise exceptions.ScenarioGetServerError + result.update({'get_server': 1}) + LOG.info('Get Server successful!') + keys = self.scenario_cfg.get('output', '').split() + values = [server] return self._push_to_outputs(keys, values) diff --git a/yardstick/benchmark/scenarios/networking/pktgen_dpdk.py b/yardstick/benchmark/scenarios/networking/pktgen_dpdk.py index ce8a7f497..9a7b975a2 100644 --- a/yardstick/benchmark/scenarios/networking/pktgen_dpdk.py +++ b/yardstick/benchmark/scenarios/networking/pktgen_dpdk.py @@ -70,39 +70,42 @@ class PktgenDPDKLatency(base.Scenario): def run(self, result): """execute the benchmark""" + options = self.scenario_cfg['options'] + eth1 = options.get("eth1", "ens4") + eth2 = options.get("eth2", "ens5") if not self.setup_done: self.setup() if not self.testpmd_args: - self.testpmd_args = utils.get_port_mac(self.client, 'eth2') + self.testpmd_args = utils.get_port_mac(self.client, eth2) if not self.pktgen_args: - server_rev_mac = utils.get_port_mac(self.server, 'eth1') - server_send_mac = utils.get_port_mac(self.server, 'eth2') - client_src_ip = utils.get_port_ip(self.client, 'eth1') - client_dst_ip = utils.get_port_ip(self.client, 'eth2') + server_rev_mac = utils.get_port_mac(self.server, eth1) + server_send_mac = utils.get_port_mac(self.server, eth2) + client_src_ip = utils.get_port_ip(self.client, eth1) + client_dst_ip = utils.get_port_ip(self.client, eth2) self.pktgen_args = [client_src_ip, client_dst_ip, server_rev_mac, server_send_mac] - options = self.scenario_cfg['options'] packetsize = options.get("packetsize", 64) rate = options.get("rate", 100) - cmd = "screen sudo -E bash ~/testpmd_fwd.sh %s " % (self.testpmd_args) + cmd = "screen sudo -E bash ~/testpmd_fwd.sh %s %s %s" % \ + (self.testpmd_args, eth1, eth2) LOG.debug("Executing command: %s", cmd) self.server.send_command(cmd) time.sleep(1) - cmd = "screen sudo -E bash ~/pktgen_dpdk.sh %s %s %s %s %s %s" % \ + cmd = "screen sudo -E bash ~/pktgen_dpdk.sh %s %s %s %s %s %s %s %s" % \ (self.pktgen_args[0], self.pktgen_args[1], self.pktgen_args[2], - self.pktgen_args[3], rate, packetsize) + self.pktgen_args[3], rate, packetsize, eth1, eth2) LOG.debug("Executing command: %s", cmd) self.client.send_command(cmd) # wait for finishing test - time.sleep(1) + time.sleep(60) cmd = r"""\ cat ~/result.log -vT \ diff --git a/yardstick/benchmark/scenarios/networking/pktgen_dpdk_latency_benchmark.bash b/yardstick/benchmark/scenarios/networking/pktgen_dpdk_latency_benchmark.bash index b872aa3df..dcd5a9bfb 100644 --- a/yardstick/benchmark/scenarios/networking/pktgen_dpdk_latency_benchmark.bash +++ b/yardstick/benchmark/scenarios/networking/pktgen_dpdk_latency_benchmark.bash @@ -7,7 +7,7 @@ # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 ############################################################################## -!/bin/sh +#!/bin/sh set -e @@ -18,6 +18,11 @@ FWD_REV_MAC=$3 # MAC address of forwarding receiver in VM B FWD_SEND_MAC=$4 # MAC address of forwarding sender in VM B RATE=$5 # packet rate in percentage PKT_SIZE=$6 # packet size +ETH1=$7 +ETH2=$8 + +DPDK_VERSION="dpdk-17.02" +PKTGEN_VERSION="pktgen-3.2.12" load_modules() @@ -31,13 +36,13 @@ load_modules() if lsmod | grep "igb_uio" &> /dev/null ; then echo "igb_uio module is loaded" else - insmod /dpdk/x86_64-native-linuxapp-gcc/kmod/igb_uio.ko + insmod /opt/tempT/$DPDK_VERSION/x86_64-native-linuxapp-gcc/kmod/igb_uio.ko fi if lsmod | grep "rte_kni" &> /dev/null ; then echo "rte_kni module is loaded" else - insmod /dpdk/x86_64-native-linuxapp-gcc/kmod/rte_kni.ko + insmod /opt/tempT/$DPDK_VERSION/x86_64-native-linuxapp-gcc/kmod/rte_kni.ko fi } @@ -48,8 +53,10 @@ change_permissions() } add_interface_to_dpdk(){ + ip link set $ETH1 down + ip link set $ETH2 down interfaces=$(lspci |grep Eth |tail -n +2 |awk '{print $1}') - /dpdk/tools/dpdk-devbind.py --bind=igb_uio $interfaces + /opt/tempT/$DPDK_VERSION/usertools/dpdk-devbind.py --bind=igb_uio $interfaces } @@ -106,20 +113,14 @@ spawn ./app/app/x86_64-native-linuxapp-gcc/pktgen -c 0x07 -n 4 -b $blacklist -- expect "Pktgen>" send "\n" expect "Pktgen>" -send "screen on\n" +send "on\n" expect "Pktgen>" set count 10 while { $count } { send "page latency\n" - expect { - timeout { send "\n" } - -regexp {..*} { - set result "${result}$expect_out(0,string)" - set timeout 1 - exp_continue - } - "Pktgen>" - } + expect -re "(..*)" + set result "${result}$expect_out(0,string)" + set timeout 1 set count [expr $count-1] } send "stop 0\n" @@ -136,7 +137,7 @@ EOF run_pktgen() { blacklist=$(lspci |grep Eth |awk '{print $1}'|head -1) - cd /pktgen-dpdk + cd /opt/tempT/$PKTGEN_VERSION touch /home/ubuntu/result.log result_log="/home/ubuntu/result.log" sudo expect /home/ubuntu/pktgen.exp $blacklist $result_log @@ -153,4 +154,3 @@ main() } main - diff --git a/yardstick/benchmark/scenarios/networking/testpmd_fwd.bash b/yardstick/benchmark/scenarios/networking/testpmd_fwd.bash index 247a8a833..30b63a734 100644 --- a/yardstick/benchmark/scenarios/networking/testpmd_fwd.bash +++ b/yardstick/benchmark/scenarios/networking/testpmd_fwd.bash @@ -13,6 +13,10 @@ set -e # Commandline arguments DST_MAC=$1 # MAC address of the peer port +ETH1=$2 +ETH2=$3 + +DPDK_VERSION="dpdk-17.02" load_modules() { @@ -25,13 +29,13 @@ load_modules() if lsmod | grep "igb_uio" &> /dev/null ; then echo "igb_uio module is loaded" else - insmod /dpdk/x86_64-native-linuxapp-gcc/kmod/igb_uio.ko + insmod /opt/tempT/$DPDK_VERSION/x86_64-native-linuxapp-gcc/kmod/igb_uio.ko fi if lsmod | grep "rte_kni" &> /dev/null ; then echo "rte_kni module is loaded" else - insmod /dpdk/x86_64-native-linuxapp-gcc/kmod/rte_kni.ko + insmod /opt/tempT/$DPDK_VERSION/x86_64-native-linuxapp-gcc/kmod/rte_kni.ko fi } @@ -42,15 +46,17 @@ change_permissions() } add_interface_to_dpdk(){ + ip link set $ETH1 down + ip link set $ETH2 down interfaces=$(lspci |grep Eth |tail -n +2 |awk '{print $1}') - /dpdk/tools/dpdk-devbind.py --bind=igb_uio $interfaces + /opt/tempT/$DPDK_VERSION/usertools//dpdk-devbind.py --bind=igb_uio $interfaces } run_testpmd() { blacklist=$(lspci |grep Eth |awk '{print $1}'|head -1) - cd /dpdk - sudo ./destdir/bin/testpmd -c 0x07 -n 4 -b $blacklist -- -a --eth-peer=1,$DST_MAC --forward-mode=mac + cd /opt/tempT/$DPDK_VERSION/x86_64-native-linuxapp-gcc/app + sudo ./testpmd -c 0x07 -n 4 -b $blacklist -- -a --eth-peer=1,$DST_MAC --forward-mode=mac } main() diff --git a/yardstick/benchmark/scenarios/networking/vnf_generic.py b/yardstick/benchmark/scenarios/networking/vnf_generic.py index 0e4785294..be2fa3f3b 100644 --- a/yardstick/benchmark/scenarios/networking/vnf_generic.py +++ b/yardstick/benchmark/scenarios/networking/vnf_generic.py @@ -14,6 +14,7 @@ import copy import logging +import time import ipaddress from itertools import chain @@ -484,3 +485,11 @@ class NetworkServiceTestCase(scenario_base.Scenario): # https://bugs.python.org/issue9400 LOG.exception("") raise RuntimeError("Error in teardown") + + def pre_run_wait_time(self, time_seconds): + """Time waited before executing the run method""" + time.sleep(time_seconds) + + def post_run_wait_time(self, time_seconds): + """Time waited after executing the run method""" + pass diff --git a/yardstick/cmd/commands/task.py b/yardstick/cmd/commands/task.py index a3488a23d..c6379e586 100644 --- a/yardstick/cmd/commands/task.py +++ b/yardstick/cmd/commands/task.py @@ -25,6 +25,7 @@ class TaskCommands(object): # pragma: no cover Set of commands to manage benchmark tasks. """ + EXIT_TEST_FAILED = 2 @cliargs("inputfile", type=str, help="path to task or suite file", nargs=1) @cliargs("--task-args", dest="task_args", @@ -48,18 +49,20 @@ class TaskCommands(object): # pragma: no cover param = change_osloobj_to_paras(args) self.output_file = param.output_file - result = {} LOG.info('Task START') try: result = Task().start(param, **kwargs) except Exception as e: # pylint: disable=broad-except self._write_error_data(e) - - if result.get('result', {}).get('criteria') == 'PASS': - LOG.info('Task SUCCESS') - else: LOG.info('Task FAILED') - raise RuntimeError('Task Failed') + raise + else: + if result.get('result', {}).get('criteria') == 'PASS': + LOG.info('Task SUCCESS') + else: + LOG.info('Task FAILED') + # exit without backtrace + raise SystemExit(self.EXIT_TEST_FAILED) def _write_error_data(self, error): data = {'status': 2, 'result': str(error)} diff --git a/yardstick/common/ansible_common.py b/yardstick/common/ansible_common.py index 38d2dd7c2..ca5a110e2 100644 --- a/yardstick/common/ansible_common.py +++ b/yardstick/common/ansible_common.py @@ -514,7 +514,7 @@ class AnsibleCommon(object): parser.add_section('defaults') parser.set('defaults', 'host_key_checking', 'False') - cfg_path = os.path.join(directory, 'setup.cfg') + cfg_path = os.path.join(directory, 'ansible.cfg') with open(cfg_path, 'w') as f: parser.write(f) diff --git a/yardstick/common/constants.py b/yardstick/common/constants.py index 153bd4bf4..8640afbae 100644 --- a/yardstick/common/constants.py +++ b/yardstick/common/constants.py @@ -152,3 +152,6 @@ IS_PUBLIC = 'is_public' # general TESTCASE_PRE = 'opnfv_yardstick_' TESTSUITE_PRE = 'opnfv_' + +# OpenStack cloud default config parameters +OS_CLOUD_DEFAULT_CONFIG = {'verify': False} diff --git a/yardstick/common/exceptions.py b/yardstick/common/exceptions.py index 8160c5b0c..04920943d 100644 --- a/yardstick/common/exceptions.py +++ b/yardstick/common/exceptions.py @@ -54,6 +54,10 @@ class YardstickException(Exception): return False +class ResourceCommandError(YardstickException): + message = 'Command: "%(command)s" Failed, stderr: "%(stderr)s"' + + class FunctionNotImplemented(YardstickException): message = ('The function "%(function_name)s" is not implemented in ' '"%(class_name)" class.') @@ -64,6 +68,11 @@ class YardstickBannedModuleImported(YardstickException): message = 'Module "%(module)s" cannnot be imported. Reason: "%(reason)s"' +class PayloadMissingAttributes(YardstickException): + message = ('Error instantiating a Payload class, missing attributes: ' + '%(missing_attributes)s') + + class HeatTemplateError(YardstickException): """Error in Heat during the stack deployment""" message = ('Error in Heat during the creation of the OpenStack stack ' @@ -82,6 +91,47 @@ class DPDKSetupDriverError(YardstickException): message = '"igb_uio" driver is not loaded' +class OVSUnsupportedVersion(YardstickException): + message = ('Unsupported OVS version "%(ovs_version)s". Please check the ' + 'config. OVS to DPDK version map: %(ovs_to_dpdk_map)s.') + + +class OVSHugepagesInfoError(YardstickException): + message = 'MemInfo cannnot be retrieved.' + + +class OVSHugepagesNotConfigured(YardstickException): + message = 'HugePages are not configured in this system.' + + +class OVSHugepagesZeroFree(YardstickException): + message = ('There are no HugePages free in this system. Total HugePages ' + 'configured: %(total_hugepages)s') + + +class OVSDeployError(YardstickException): + message = 'OVS deploy tool failed with error: %(stderr)s.' + + +class OVSSetupError(YardstickException): + message = 'OVS setup error. Command: %(command)s. Error: %(error)s.' + + +class LibvirtCreateError(YardstickException): + message = 'Error creating the virtual machine. Error: %(error)s.' + + +class LibvirtQemuImageBaseImageNotPresent(YardstickException): + message = ('Error creating the qemu image for %(vm_image)s. Base image: ' + '%(base_image)s. Base image not present in execution host or ' + 'remote host.') + + +class LibvirtQemuImageCreateError(YardstickException): + message = ('Error creating the qemu image for %(vm_image)s. Base image: ' + '%(base_image)s. Error: %(error)s.') + + class ScenarioConfigContextNameNotFound(YardstickException): message = 'Context name "%(context_name)s" not found' @@ -102,6 +152,14 @@ class TaskRenderError(YardstickException): message = 'Failed to render template:\n%(input_task)s' +class TimerTimeout(YardstickException): + message = 'Timer timeout expired, %(timeout)s seconds' + + +class WaitTimeout(YardstickException): + message = 'Wait timeout while waiting for condition' + + class ScenarioCreateNetworkError(YardstickException): message = 'Create Neutron Network Scenario failed' @@ -124,3 +182,51 @@ class UnsupportedPodFormatError(YardstickException): class ScenarioCreateRouterError(YardstickException): message = 'Create Neutron Router Scenario failed' + + +class ScenarioRemoveRouterIntError(YardstickException): + message = 'Remove Neutron Router Interface Scenario failed' + + +class ScenarioCreateFloatingIPError(YardstickException): + message = 'Create Neutron Floating IP Scenario failed' + + +class ScenarioDeleteFloatingIPError(YardstickException): + message = 'Delete Neutron Floating IP Scenario failed' + + +class ScenarioCreateSecurityGroupError(YardstickException): + message = 'Create Neutron Security Group Scenario failed' + + +class ScenarioDeleteNetworkError(YardstickException): + message = 'Delete Neutron Network Scenario failed' + + +class ScenarioCreateServerError(YardstickException): + message = 'Nova Create Server Scenario failed' + + +class ScenarioDeleteServerError(YardstickException): + message = 'Delete Server Scenario failed' + + +class ScenarioCreateKeypairError(YardstickException): + message = 'Nova Create Keypair Scenario failed' + + +class ScenarioDeleteKeypairError(YardstickException): + message = 'Nova Delete Keypair Scenario failed' + + +class ScenarioAttachVolumeError(YardstickException): + message = 'Nova Attach Volume Scenario failed' + + +class ScenarioGetServerError(YardstickException): + message = 'Nova Get Server Scenario failed' + + +class ScenarioGetFlavorError(YardstickException): + message = 'Nova Get Falvor Scenario failed' diff --git a/yardstick/common/messaging/__init__.py b/yardstick/common/messaging/__init__.py new file mode 100644 index 000000000..f0f012ec3 --- /dev/null +++ b/yardstick/common/messaging/__init__.py @@ -0,0 +1,36 @@ +# Copyright (c) 2018 Intel Corporation +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# MQ is statically configured: +# - MQ service: RabbitMQ +# - user/password: yardstick/yardstick +# - host:port: localhost:5672 +MQ_USER = 'yardstick' +MQ_PASS = 'yardstick' +MQ_SERVICE = 'rabbit' +SERVER = 'localhost' +PORT = 5672 +TRANSPORT_URL = (MQ_SERVICE + '://' + MQ_USER + ':' + MQ_PASS + '@' + SERVER + + ':' + str(PORT) + '/') + +# RPC server. +RPC_SERVER_EXECUTOR = 'threading' + +# Topics. +RUNNER = 'runner' + +# Methods. +# RUNNER methods: +RUNNER_INFO = 'runner_info' +RUNNER_LOOP = 'runner_loop' diff --git a/yardstick/common/messaging/consumer.py b/yardstick/common/messaging/consumer.py new file mode 100644 index 000000000..24ec6f184 --- /dev/null +++ b/yardstick/common/messaging/consumer.py @@ -0,0 +1,85 @@ +# Copyright (c) 2018 Intel Corporation +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import abc +import logging + +from oslo_config import cfg +import oslo_messaging +import six + +from yardstick.common import messaging + + +LOG = logging.getLogger(__name__) + + +@six.add_metaclass(abc.ABCMeta) +class NotificationHandler(object): + """Abstract class to define a endpoint object for a MessagingConsumer""" + + def __init__(self, _id, ctx_pids, queue): + self._id = _id + self._ctx_pids = ctx_pids + self._queue = queue + + +@six.add_metaclass(abc.ABCMeta) +class MessagingConsumer(object): + """Abstract class to implement a MQ consumer + + This abstract class allows a class implementing this interface to receive + the messages published by a `MessagingNotifier`. + """ + + def __init__(self, topic, pids, endpoints, fanout=True): + """Init function. + + :param topic: (string) MQ exchange topic + :param pids: (list of int) list of PIDs of the processes implementing + the MQ Notifier which will be in the message context + :param endpoints: (list of class) list of classes implementing the + methods (see `MessagingNotifier.send_message) used by + the Notifier + :param fanout: (bool) MQ clients may request that a copy of the message + be delivered to all servers listening on a topic by + setting fanout to ``True``, rather than just one of them + :returns: `MessagingConsumer` class object + """ + + self._pids = pids + self._endpoints = endpoints + self._transport = oslo_messaging.get_rpc_transport( + cfg.CONF, url=messaging.TRANSPORT_URL) + self._target = oslo_messaging.Target(topic=topic, fanout=fanout, + server=messaging.SERVER) + self._server = oslo_messaging.get_rpc_server( + self._transport, self._target, self._endpoints, + executor=messaging.RPC_SERVER_EXECUTOR, + access_policy=oslo_messaging.DefaultRPCAccessPolicy) + + def start_rpc_server(self): + """Start the RPC server.""" + if self._server: + self._server.start() + + def stop_rpc_server(self): + """Stop the RPC server.""" + if self._server: + self._server.stop() + + def wait(self): + """Wait for message processing to complete (blocking).""" + if self._server: + self._server.wait() diff --git a/yardstick/common/messaging/payloads.py b/yardstick/common/messaging/payloads.py new file mode 100644 index 000000000..d29d79808 --- /dev/null +++ b/yardstick/common/messaging/payloads.py @@ -0,0 +1,53 @@ +# Copyright (c) 2018 Intel Corporation +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import abc + +import six + +from yardstick.common import exceptions + + +@six.add_metaclass(abc.ABCMeta) +class Payload(object): + """Base Payload class to transfer data through the MQ service""" + + REQUIRED_FIELDS = {'version'} + + def __init__(self, **kwargs): + """Init method + + :param kwargs: (dictionary) attributes and values of the object + :returns: Payload object + """ + + if not all(req_field in kwargs for req_field in self.REQUIRED_FIELDS): + _attrs = set(kwargs) - self.REQUIRED_FIELDS + missing_attributes = ', '.join(str(_attr) for _attr in _attrs) + raise exceptions.PayloadMissingAttributes( + missing_attributes=missing_attributes) + + for name, value in kwargs.items(): + setattr(self, name, value) + + self._fields = set(kwargs.keys()) + + def obj_to_dict(self): + """Returns a dictionary with the attributes of the object""" + return {field: getattr(self, field) for field in self._fields} + + @classmethod + def dict_to_obj(cls, _dict): + """Returns a Payload object built from the dictionary elements""" + return cls(**_dict) diff --git a/yardstick/common/messaging/producer.py b/yardstick/common/messaging/producer.py new file mode 100644 index 000000000..b6adc0c17 --- /dev/null +++ b/yardstick/common/messaging/producer.py @@ -0,0 +1,70 @@ +# Copyright (c) 2018 Intel Corporation +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import abc +import logging +import os + +from oslo_config import cfg +import oslo_messaging +import six + +from yardstick.common import messaging + + +LOG = logging.getLogger(__name__) + + +@six.add_metaclass(abc.ABCMeta) +class MessagingProducer(object): + """Abstract class to implement a MQ producer + + This abstract class allows a class implementing this interface to publish + messages in a message queue. + """ + + def __init__(self, topic, pid=os.getpid(), fanout=True): + """Init function. + + :param topic: (string) MQ exchange topic + :param pid: (int) PID of the process implementing this MQ Notifier + :param fanout: (bool) MQ clients may request that a copy of the message + be delivered to all servers listening on a topic by + setting fanout to ``True``, rather than just one of them + :returns: `MessagingNotifier` class object + """ + self._topic = topic + self._pid = pid + self._fanout = fanout + self._transport = oslo_messaging.get_rpc_transport( + cfg.CONF, url=messaging.TRANSPORT_URL) + self._target = oslo_messaging.Target(topic=topic, fanout=fanout, + server=messaging.SERVER) + self._notifier = oslo_messaging.RPCClient(self._transport, + self._target) + + def send_message(self, method, payload): + """Send a cast message, that will invoke a method without blocking. + + The cast() method is used to invoke an RPC method that does not return + a value. cast() RPC requests may be broadcast to all Servers listening + on a given topic by setting the fanout Target property to ``True``. + + :param methos: (string) method name, that must be implemented in the + consumer endpoints + :param payload: (subclass `Payload`) payload content + """ + self._notifier.cast({'pid': self._pid}, + method, + **payload.obj_to_dict()) diff --git a/yardstick/common/openstack_utils.py b/yardstick/common/openstack_utils.py index a4fd4e550..53f0ccc34 100644 --- a/yardstick/common/openstack_utils.py +++ b/yardstick/common/openstack_utils.py @@ -7,20 +7,21 @@ # http://www.apache.org/licenses/LICENSE-2.0 ############################################################################## +import copy +import logging import os -import time import sys -import logging +from cinderclient import client as cinderclient +from novaclient import client as novaclient +from glanceclient import client as glanceclient from keystoneauth1 import loading from keystoneauth1 import session +from neutronclient.neutron import client as neutronclient import shade from shade import exc -from cinderclient import client as cinderclient -from novaclient import client as novaclient -from glanceclient import client as glanceclient -from neutronclient.neutron import client as neutronclient +from yardstick.common import constants log = logging.getLogger(__name__) @@ -156,204 +157,205 @@ def get_glance_client(): # pragma: no cover return glanceclient.Client(get_glance_client_version(), session=sess) -def get_shade_client(): - return shade.openstack_cloud() +def get_shade_client(**os_cloud_config): + """Get Shade OpenStack cloud client + + By default, the input parameters given to "shade.openstack_cloud" method + are stored in "constants.OS_CLOUD_DEFAULT_CONFIG". The input parameters + passed in this function, "os_cloud_config", will overwrite the default + ones. + + :param os_cloud_config: (kwargs) input arguments for + "shade.openstack_cloud" method. + :return: ``shade.OpenStackCloud`` object. + """ + params = copy.deepcopy(constants.OS_CLOUD_DEFAULT_CONFIG) + params.update(os_cloud_config) + return shade.openstack_cloud(**params) # ********************************************* # NOVA # ********************************************* -def get_instances(nova_client): - try: - return nova_client.servers.list(search_opts={'all_tenants': 1}) - except Exception: # pylint: disable=broad-except - log.exception("Error [get_instances(nova_client)]") - - -def get_instance_status(nova_client, instance): # pragma: no cover - try: - return nova_client.servers.get(instance.id).status - except Exception: # pylint: disable=broad-except - log.exception("Error [get_instance_status(nova_client)]") +def create_keypair(shade_client, name, public_key=None): + """Create a new keypair. + :param name: Name of the keypair being created. + :param public_key: Public key for the new keypair. -def get_instance_by_name(nova_client, instance_name): # pragma: no cover - try: - return nova_client.servers.find(name=instance_name) - except Exception: # pylint: disable=broad-except - log.exception("Error [get_instance_by_name(nova_client, '%s')]", - instance_name) - - -def get_aggregates(nova_client): # pragma: no cover - try: - return nova_client.aggregates.list() - except Exception: # pylint: disable=broad-except - log.exception("Error [get_aggregates(nova_client)]") - - -def get_availability_zones(nova_client): # pragma: no cover + :return: Created keypair. + """ try: - return nova_client.availability_zones.list() - except Exception: # pylint: disable=broad-except - log.exception("Error [get_availability_zones(nova_client)]") + return shade_client.create_keypair(name, public_key=public_key) + except exc.OpenStackCloudException as o_exc: + log.error("Error [create_keypair(shade_client)]. " + "Exception message, '%s'", o_exc.orig_message) -def get_availability_zone_names(nova_client): # pragma: no cover +def create_instance_and_wait_for_active(shade_client, name, image, + flavor, auto_ip=True, ips=None, + ip_pool=None, root_volume=None, + terminate_volume=False, wait=True, + timeout=180, reuse_ips=True, + network=None, boot_from_volume=False, + volume_size='20', boot_volume=None, + volumes=None, nat_destination=None, + **kwargs): + """Create a virtual server instance. + + :param name:(string) Name of the server. + :param image:(dict) Image dict, name or ID to boot with. Image is required + unless boot_volume is given. + :param flavor:(dict) Flavor dict, name or ID to boot onto. + :param auto_ip: Whether to take actions to find a routable IP for + the server. + :param ips: List of IPs to attach to the server. + :param ip_pool:(string) Name of the network or floating IP pool to get an + address from. + :param root_volume:(string) Name or ID of a volume to boot from. + (defaults to None - deprecated, use boot_volume) + :param boot_volume:(string) Name or ID of a volume to boot from. + :param terminate_volume:(bool) If booting from a volume, whether it should + be deleted when the server is destroyed. + :param volumes:(optional) A list of volumes to attach to the server. + :param wait:(optional) Wait for the address to appear as assigned to the server. + :param timeout: Seconds to wait, defaults to 60. + :param reuse_ips:(bool)Whether to attempt to reuse pre-existing + floating ips should a floating IP be needed. + :param network:(dict) Network dict or name or ID to attach the server to. + Mutually exclusive with the nics parameter. Can also be be + a list of network names or IDs or network dicts. + :param boot_from_volume:(bool) Whether to boot from volume. 'boot_volume' + implies True, but boot_from_volume=True with + no boot_volume is valid and will create a + volume from the image and use that. + :param volume_size: When booting an image from volume, how big should + the created volume be? + :param nat_destination: Which network should a created floating IP + be attached to, if it's not possible to infer from + the cloud's configuration. + :param meta:(optional) A dict of arbitrary key/value metadata to store for + this server. Both keys and values must be <=255 characters. + :param reservation_id: A UUID for the set of servers being requested. + :param min_count:(optional extension) The minimum number of servers to + launch. + :param max_count:(optional extension) The maximum number of servers to + launch. + :param security_groups: A list of security group names. + :param userdata: User data to pass to be exposed by the metadata server + this can be a file type object as well or a string. + :param key_name:(optional extension) Name of previously created keypair to + inject into the instance. + :param availability_zone: Name of the availability zone for instance + placement. + :param block_device_mapping:(optional) A dict of block device mappings for + this server. + :param block_device_mapping_v2:(optional) A dict of block device mappings + for this server. + :param nics:(optional extension) An ordered list of nics to be added to + this server, with information about connected networks, fixed + IPs, port etc. + :param scheduler_hints:(optional extension) Arbitrary key-value pairs + specified by the client to help boot an instance. + :param config_drive:(optional extension) Value for config drive either + boolean, or volume-id. + :param disk_config:(optional extension) Control how the disk is partitioned + when the server is created. Possible values are 'AUTO' + or 'MANUAL'. + :param admin_pass:(optional extension) Add a user supplied admin password. + + :returns: The created server. + """ try: - return [az.zoneName for az in get_availability_zones(nova_client)] - except Exception: # pylint: disable=broad-except - log.exception("Error [get_availability_zone_names(nova_client)]") + return shade_client.create_server( + name, image, flavor, auto_ip=auto_ip, ips=ips, ip_pool=ip_pool, + root_volume=root_volume, terminate_volume=terminate_volume, + wait=wait, timeout=timeout, reuse_ips=reuse_ips, network=network, + boot_from_volume=boot_from_volume, volume_size=volume_size, + boot_volume=boot_volume, volumes=volumes, + nat_destination=nat_destination, **kwargs) + except exc.OpenStackCloudException as o_exc: + log.error("Error [create_instance(shade_client)]. " + "Exception message, '%s'", o_exc.orig_message) -def create_aggregate(nova_client, aggregate_name, av_zone): # pragma: no cover - try: - nova_client.aggregates.create(aggregate_name, av_zone) - except Exception: # pylint: disable=broad-except - log.exception("Error [create_aggregate(nova_client, %s, %s)]", - aggregate_name, av_zone) - return False - else: - return True +def attach_volume_to_server(shade_client, server_name_or_id, volume_name_or_id, + device=None, wait=True, timeout=None): + """Attach a volume to a server. + This will attach a volume, described by the passed in volume + dict, to the server described by the passed in server dict on the named + device on the server. -def get_aggregate_id(nova_client, aggregate_name): # pragma: no cover - try: - aggregates = get_aggregates(nova_client) - _id = next((ag.id for ag in aggregates if ag.name == aggregate_name)) - except Exception: # pylint: disable=broad-except - log.exception("Error [get_aggregate_id(nova_client, %s)]", - aggregate_name) - else: - return _id + If the volume is already attached to the server, or generally not + available, then an exception is raised. To re-attach to a server, + but under a different device, the user must detach it first. + :param server_name_or_id:(string) The server name or id to attach to. + :param volume_name_or_id:(string) The volume name or id to attach. + :param device:(string) The device name where the volume will attach. + :param wait:(bool) If true, waits for volume to be attached. + :param timeout: Seconds to wait for volume attachment. None is forever. -def add_host_to_aggregate(nova_client, aggregate_name, - compute_host): # pragma: no cover + :returns: True if attached successful, False otherwise. + """ try: - aggregate_id = get_aggregate_id(nova_client, aggregate_name) - nova_client.aggregates.add_host(aggregate_id, compute_host) - except Exception: # pylint: disable=broad-except - log.exception("Error [add_host_to_aggregate(nova_client, %s, %s)]", - aggregate_name, compute_host) - return False - else: + server = shade_client.get_server(name_or_id=server_name_or_id) + volume = shade_client.get_volume(volume_name_or_id) + shade_client.attach_volume( + server, volume, device=device, wait=wait, timeout=timeout) return True - - -def create_aggregate_with_host(nova_client, aggregate_name, av_zone, - compute_host): # pragma: no cover - try: - create_aggregate(nova_client, aggregate_name, av_zone) - add_host_to_aggregate(nova_client, aggregate_name, compute_host) - except Exception: # pylint: disable=broad-except - log.exception("Error [create_aggregate_with_host(" - "nova_client, %s, %s, %s)]", - aggregate_name, av_zone, compute_host) + except exc.OpenStackCloudException as o_exc: + log.error("Error [attach_volume_to_server(shade_client)]. " + "Exception message: %s", o_exc.orig_message) return False - else: - return True -def create_keypair(name, key_path=None): # pragma: no cover - try: - with open(key_path) as fpubkey: - keypair = get_nova_client().keypairs.create( - name=name, public_key=fpubkey.read()) - return keypair - except Exception: # pylint: disable=broad-except - log.exception("Error [create_keypair(nova_client)]") - - -def create_instance(json_body): # pragma: no cover - try: - return get_nova_client().servers.create(**json_body) - except Exception: # pylint: disable=broad-except - log.exception("Error create instance failed") - return None - - -def create_instance_and_wait_for_active(json_body): # pragma: no cover - SLEEP = 3 - VM_BOOT_TIMEOUT = 180 - nova_client = get_nova_client() - instance = create_instance(json_body) - for _ in range(int(VM_BOOT_TIMEOUT / SLEEP)): - status = get_instance_status(nova_client, instance) - if status.lower() == "active": - return instance - elif status.lower() == "error": - log.error("The instance went to ERROR status.") - return None - time.sleep(SLEEP) - log.error("Timeout booting the instance.") - return None - - -def attach_server_volume(server_id, volume_id, - device=None): # pragma: no cover - try: - get_nova_client().volumes.create_server_volume(server_id, - volume_id, device) - except Exception: # pylint: disable=broad-except - log.exception("Error [attach_server_volume(nova_client, '%s', '%s')]", - server_id, volume_id) - return False - else: - return True - +def delete_instance(shade_client, name_or_id, wait=False, timeout=180, + delete_ips=False, delete_ip_retry=1): + """Delete a server instance. -def delete_instance(nova_client, instance_id): # pragma: no cover - try: - nova_client.servers.force_delete(instance_id) - except Exception: # pylint: disable=broad-except - log.exception("Error [delete_instance(nova_client, '%s')]", - instance_id) - return False - else: - return True - - -def remove_host_from_aggregate(nova_client, aggregate_name, - compute_host): # pragma: no cover + :param name_or_id: name or ID of the server to delete + :param wait:(bool) If true, waits for server to be deleted. + :param timeout:(int) Seconds to wait for server deletion. + :param delete_ips:(bool) If true, deletes any floating IPs associated with + the instance. + :param delete_ip_retry:(int) Number of times to retry deleting + any floating ips, should the first try be + unsuccessful. + :returns: True if delete succeeded, False otherwise. + """ try: - aggregate_id = get_aggregate_id(nova_client, aggregate_name) - nova_client.aggregates.remove_host(aggregate_id, compute_host) - except Exception: # pylint: disable=broad-except - log.exception("Error remove_host_from_aggregate(nova_client, %s, %s)", - aggregate_name, compute_host) + return shade_client.delete_server( + name_or_id, wait=wait, timeout=timeout, delete_ips=delete_ips, + delete_ip_retry=delete_ip_retry) + except exc.OpenStackCloudException as o_exc: + log.error("Error [delete_instance(shade_client, '%s')]. " + "Exception message: %s", name_or_id, + o_exc.orig_message) return False - else: - return True -def remove_hosts_from_aggregate(nova_client, - aggregate_name): # pragma: no cover - aggregate_id = get_aggregate_id(nova_client, aggregate_name) - hosts = nova_client.aggregates.get(aggregate_id).hosts - assert( - all(remove_host_from_aggregate(nova_client, aggregate_name, host) - for host in hosts)) +def get_server(shade_client, name_or_id=None, filters=None, detailed=False, + bare=False): + """Get a server by name or ID. + :param name_or_id: Name or ID of the server. + :param filters:(dict) A dictionary of meta data to use for further + filtering. + :param detailed:(bool) Whether or not to add detailed additional + information. + :param bare:(bool) Whether to skip adding any additional information to the + server record. -def delete_aggregate(nova_client, aggregate_name): # pragma: no cover - try: - remove_hosts_from_aggregate(nova_client, aggregate_name) - nova_client.aggregates.delete(aggregate_name) - except Exception: # pylint: disable=broad-except - log.exception("Error [delete_aggregate(nova_client, %s)]", - aggregate_name) - return False - else: - return True - - -def get_server_by_name(name): # pragma: no cover + :returns: A server ``munch.Munch`` or None if no matching server is found. + """ try: - return get_nova_client().servers.list(search_opts={'name': name})[0] - except IndexError: - log.exception('Failed to get nova client') - raise + return shade_client.get_server(name_or_id=name_or_id, filters=filters, + detailed=detailed, bare=bare) + except exc.OpenStackCloudException as o_exc: + log.error("Error [get_server(shade_client, '%s')]. " + "Exception message: %s", name_or_id, o_exc.orig_message) def create_flavor(name, ram, vcpus, disk, **kwargs): # pragma: no cover @@ -366,14 +368,6 @@ def create_flavor(name, ram, vcpus, disk, **kwargs): # pragma: no cover return None -def get_image_by_name(name): # pragma: no cover - images = get_nova_client().images.list() - try: - return next((a for a in images if a.name == name)) - except StopIteration: - log.exception('No image matched') - - def get_flavor_id(nova_client, flavor_name): # pragma: no cover flavors = nova_client.flavors.list(detailed=True) flavor_id = '' @@ -384,27 +378,22 @@ def get_flavor_id(nova_client, flavor_name): # pragma: no cover return flavor_id -def get_flavor_by_name(name): # pragma: no cover - flavors = get_nova_client().flavors.list() - try: - return next((a for a in flavors if a.name == name)) - except StopIteration: - log.exception('No flavor matched') - +def get_flavor(shade_client, name_or_id, filters=None, get_extra=True): + """Get a flavor by name or ID. -def check_status(status, name, iterations, interval): # pragma: no cover - for _ in range(iterations): - try: - server = get_server_by_name(name) - except IndexError: - log.error('Cannot found %s server', name) - raise + :param name_or_id: Name or ID of the flavor. + :param filters: A dictionary of meta data to use for further filtering. + :param get_extra: Whether or not the list_flavors call should get the extra + flavor specs. - if server.status == status: - return True - - time.sleep(interval) - return False + :returns: A flavor ``munch.Munch`` or None if no matching flavor is found. + """ + try: + return shade_client.get_flavor(name_or_id, filters=filters, + get_extra=get_extra) + except exc.OpenStackCloudException as o_exc: + log.error("Error [get_flavor(shade_client, '%s')]. " + "Exception message: %s", name_or_id, o_exc.orig_message) def delete_flavor(flavor_id): # pragma: no cover @@ -417,24 +406,24 @@ def delete_flavor(flavor_id): # pragma: no cover return True -def delete_keypair(nova_client, key): # pragma: no cover +def delete_keypair(shade_client, name): + """Delete a keypair. + + :param name: Name of the keypair to delete. + + :returns: True if delete succeeded, False otherwise. + """ try: - nova_client.keypairs.delete(key=key) - return True - except Exception: # pylint: disable=broad-except - log.exception("Error [delete_keypair(nova_client)]") + return shade_client.delete_keypair(name) + except exc.OpenStackCloudException as o_exc: + log.error("Error [delete_neutron_router(shade_client, '%s')]. " + "Exception message: %s", name, o_exc.orig_message) return False # ********************************************* # NEUTRON # ********************************************* -def get_network_id(shade_client, network_name): - networks = shade_client.list_networks({'name': network_name}) - if networks: - return networks[0]['id'] - - def create_neutron_net(shade_client, network_name, shared=False, admin_state_up=True, external=False, provider=None, project_id=None): @@ -563,151 +552,174 @@ def remove_gateway_router(neutron_client, router_id): # pragma: no cover return False -def remove_interface_router(neutron_client, router_id, subnet_id, - **json_body): # pragma: no cover - json_body.update({"subnet_id": subnet_id}) - try: - neutron_client.remove_interface_router(router=router_id, - body=json_body) - return True - except Exception: # pylint: disable=broad-except - log.error("Error [remove_interface_router(neutron_client, '%s', " - "'%s')]", router_id, subnet_id) - return False +def remove_router_interface(shade_client, router, subnet_id=None, + port_id=None): + """Detach a subnet from an internal router interface. + At least one of subnet_id or port_id must be supplied. If you specify both + subnet and port ID, the subnet ID must correspond to the subnet ID of the + first IP address on the port specified by the port ID. + Otherwise an error occurs. -def create_floating_ip(neutron_client, extnet_id): # pragma: no cover - props = {'floating_network_id': extnet_id} - try: - ip_json = neutron_client.create_floatingip({'floatingip': props}) - fip_addr = ip_json['floatingip']['floating_ip_address'] - fip_id = ip_json['floatingip']['id'] - except Exception: # pylint: disable=broad-except - log.error("Error [create_floating_ip(neutron_client)]") - return None - return {'fip_addr': fip_addr, 'fip_id': fip_id} - - -def delete_floating_ip(nova_client, floatingip_id): # pragma: no cover + :param router: The dict object of the router being changed + :param subnet_id:(string) The ID of the subnet to use for the interface + :param port_id:(string) The ID of the port to use for the interface + :returns: True on success + """ try: - nova_client.floating_ips.delete(floatingip_id) + shade_client.remove_router_interface( + router, subnet_id=subnet_id, port_id=port_id) return True - except Exception: # pylint: disable=broad-except - log.error("Error [delete_floating_ip(nova_client, '%s')]", - floatingip_id) + except exc.OpenStackCloudException as o_exc: + log.error("Error [remove_interface_router(shade_client)]. " + "Exception message: %s", o_exc.orig_message) return False -def get_security_groups(neutron_client): # pragma: no cover +def create_floating_ip(shade_client, network_name_or_id=None, server=None, + fixed_address=None, nat_destination=None, + port=None, wait=False, timeout=60): + """Allocate a new floating IP from a network or a pool. + + :param network_name_or_id: Name or ID of the network + that the floating IP should come from. + :param server: Server dict for the server to create + the IP for and to which it should be attached. + :param fixed_address: Fixed IP to attach the floating ip to. + :param nat_destination: Name or ID of the network + that the fixed IP to attach the floating + IP to should be on. + :param port: The port ID that the floating IP should be + attached to. Specifying a port conflicts with specifying a + server,fixed_address or nat_destination. + :param wait: Whether to wait for the IP to be active.Only applies + if a server is provided. + :param timeout: How long to wait for the IP to be active.Only + applies if a server is provided. + + :returns:Floating IP id and address + """ try: - security_groups = neutron_client.list_security_groups()[ - 'security_groups'] - return security_groups - except Exception: # pylint: disable=broad-except - log.error("Error [get_security_groups(neutron_client)]") - return None - - -def get_security_group_id(neutron_client, sg_name): # pragma: no cover - security_groups = get_security_groups(neutron_client) - id = '' - for sg in security_groups: - if sg['name'] == sg_name: - id = sg['id'] - break - return id + fip = shade_client.create_floating_ip( + network=network_name_or_id, server=server, + fixed_address=fixed_address, nat_destination=nat_destination, + port=port, wait=wait, timeout=timeout) + return {'fip_addr': fip['floating_ip_address'], 'fip_id': fip['id']} + except exc.OpenStackCloudException as o_exc: + log.error("Error [create_floating_ip(shade_client)]. " + "Exception message: %s", o_exc.orig_message) -def create_security_group(neutron_client, sg_name, - sg_description): # pragma: no cover - json_body = {'security_group': {'name': sg_name, - 'description': sg_description}} +def delete_floating_ip(shade_client, floating_ip_id, retry=1): try: - secgroup = neutron_client.create_security_group(json_body) - return secgroup['security_group'] - except Exception: # pylint: disable=broad-except - log.error("Error [create_security_group(neutron_client, '%s', " - "'%s')]", sg_name, sg_description) - return None + return shade_client.delete_floating_ip(floating_ip_id=floating_ip_id, + retry=retry) + except exc.OpenStackCloudException as o_exc: + log.error("Error [delete_floating_ip(shade_client,'%s')]. " + "Exception message: %s", floating_ip_id, o_exc.orig_message) + return False -def create_secgroup_rule(neutron_client, sg_id, direction, protocol, - port_range_min=None, port_range_max=None, - **json_body): # pragma: no cover - # We create a security group in 2 steps - # 1 - we check the format and set the json body accordingly - # 2 - we call neturon client to create the security group - - # Format check - json_body.update({'security_group_rule': {'direction': direction, - 'security_group_id': sg_id, 'protocol': protocol}}) - # parameters may be - # - both None => we do nothing - # - both Not None => we add them to the json description - # but one cannot be None is the other is not None - if (port_range_min is not None and port_range_max is not None): - # add port_range in json description - json_body['security_group_rule']['port_range_min'] = port_range_min - json_body['security_group_rule']['port_range_max'] = port_range_max - log.debug("Security_group format set (port range included)") - else: - # either both port range are set to None => do nothing - # or one is set but not the other => log it and return False - if port_range_min is None and port_range_max is None: - log.debug("Security_group format set (no port range mentioned)") - else: - log.error("Bad security group format." - "One of the port range is not properly set:" - "range min: %s, range max: %s", port_range_min, - port_range_max) - return False +def create_security_group_rule(shade_client, secgroup_name_or_id, + port_range_min=None, port_range_max=None, + protocol=None, remote_ip_prefix=None, + remote_group_id=None, direction='ingress', + ethertype='IPv4', project_id=None): + """Create a new security group rule + + :param secgroup_name_or_id:(string) The security group name or ID to + associate with this security group rule. If a + non-unique group name is given, an exception is + raised. + :param port_range_min:(int) The minimum port number in the range that is + matched by the security group rule. If the protocol + is TCP or UDP, this value must be less than or equal + to the port_range_max attribute value. If nova is + used by the cloud provider for security groups, then + a value of None will be transformed to -1. + :param port_range_max:(int) The maximum port number in the range that is + matched by the security group rule. The + port_range_min attribute constrains the + port_range_max attribute. If nova is used by the + cloud provider for security groups, then a value of + None will be transformed to -1. + :param protocol:(string) The protocol that is matched by the security group + rule. Valid values are None, tcp, udp, and icmp. + :param remote_ip_prefix:(string) The remote IP prefix to be associated with + this security group rule. This attribute matches + the specified IP prefix as the source IP address of + the IP packet. + :param remote_group_id:(string) The remote group ID to be associated with + this security group rule. + :param direction:(string) Ingress or egress: The direction in which the + security group rule is applied. + :param ethertype:(string) Must be IPv4 or IPv6, and addresses represented + in CIDR must match the ingress or egress rules. + :param project_id:(string) Specify the project ID this security group will + be created on (admin-only). + + :returns: True on success. + """ - # Create security group using neutron client try: - neutron_client.create_security_group_rule(json_body) + shade_client.create_security_group_rule( + secgroup_name_or_id, port_range_min=port_range_min, + port_range_max=port_range_max, protocol=protocol, + remote_ip_prefix=remote_ip_prefix, remote_group_id=remote_group_id, + direction=direction, ethertype=ethertype, project_id=project_id) return True - except Exception: # pylint: disable=broad-except - log.exception("Impossible to create_security_group_rule," - "security group rule probably already exists") + except exc.OpenStackCloudException as op_exc: + log.error("Failed to create_security_group_rule(shade_client). " + "Exception message: %s", op_exc.orig_message) return False -def create_security_group_full(neutron_client, sg_name, - sg_description): # pragma: no cover - sg_id = get_security_group_id(neutron_client, sg_name) - if sg_id != '': +def create_security_group_full(shade_client, sg_name, + sg_description, project_id=None): + security_group = shade_client.get_security_group(sg_name) + + if security_group: log.info("Using existing security group '%s'...", sg_name) - else: - log.info("Creating security group '%s'...", sg_name) - SECGROUP = create_security_group(neutron_client, - sg_name, - sg_description) - if not SECGROUP: - log.error("Failed to create the security group...") - return None - - sg_id = SECGROUP['id'] - - log.debug("Security group '%s' with ID=%s created successfully.", - SECGROUP['name'], sg_id) - - log.debug("Adding ICMP rules in security group '%s'...", sg_name) - if not create_secgroup_rule(neutron_client, sg_id, - 'ingress', 'icmp'): - log.error("Failed to create the security group rule...") - return None - - log.debug("Adding SSH rules in security group '%s'...", sg_name) - if not create_secgroup_rule( - neutron_client, sg_id, 'ingress', 'tcp', '22', '22'): - log.error("Failed to create the security group rule...") - return None - - if not create_secgroup_rule( - neutron_client, sg_id, 'egress', 'tcp', '22', '22'): - log.error("Failed to create the security group rule...") - return None - return sg_id + return security_group['id'] + + log.info("Creating security group '%s'...", sg_name) + try: + security_group = shade_client.create_security_group( + sg_name, sg_description, project_id=project_id) + except (exc.OpenStackCloudException, + exc.OpenStackCloudUnavailableFeature) as op_exc: + log.error("Error [create_security_group(shade_client, %s, %s)]. " + "Exception message: %s", sg_name, sg_description, + op_exc.orig_message) + return + + log.debug("Security group '%s' with ID=%s created successfully.", + security_group['name'], security_group['id']) + + log.debug("Adding ICMP rules in security group '%s'...", sg_name) + if not create_security_group_rule(shade_client, security_group['id'], + direction='ingress', protocol='icmp'): + log.error("Failed to create the security group rule...") + shade_client.delete_security_group(sg_name) + return + + log.debug("Adding SSH rules in security group '%s'...", sg_name) + if not create_security_group_rule(shade_client, security_group['id'], + direction='ingress', protocol='tcp', + port_range_min='22', + port_range_max='22'): + log.error("Failed to create the security group rule...") + shade_client.delete_security_group(sg_name) + return + + if not create_security_group_rule(shade_client, security_group['id'], + direction='egress', protocol='tcp', + port_range_min='22', + port_range_max='22'): + log.error("Failed to create the security group rule...") + shade_client.delete_security_group(sg_name) + return + return security_group['id'] # ********************************************* @@ -757,6 +769,18 @@ def delete_image(glance_client, image_id): # pragma: no cover return True +def list_images(shade_client=None): + if shade_client is None: + shade_client = get_shade_client() + + try: + return shade_client.list_images() + except exc.OpenStackCloudException as o_exc: + log.error("Error [list_images(shade_client)]." + "Exception message, '%s'", o_exc.orig_message) + return False + + # ********************************************* # CINDER # ********************************************* diff --git a/yardstick/common/utils.py b/yardstick/common/utils.py index 357f66be8..108ee17bc 100644 --- a/yardstick/common/utils.py +++ b/yardstick/common/utils.py @@ -23,9 +23,11 @@ import logging import os import random import re +import signal import socket import subprocess import sys +import time import six from flask import jsonify @@ -34,6 +36,8 @@ from oslo_serialization import jsonutils from oslo_utils import encodeutils import yardstick +from yardstick.common import exceptions + logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) @@ -136,6 +140,11 @@ def source_env(env_file): p = subprocess.Popen(". %s; env" % env_file, stdout=subprocess.PIPE, shell=True) output = p.communicate()[0] + + # sometimes output type would be binary_type, and it don't have splitlines + # method, so we need to decode + if isinstance(output, six.binary_type): + output = encodeutils.safe_decode(output) env = dict(line.split('=', 1) for line in output.splitlines() if '=' in line) os.environ.update(env) return env @@ -400,15 +409,24 @@ class ErrorClass(object): class Timer(object): - def __init__(self): + def __init__(self, timeout=None): super(Timer, self).__init__() self.start = self.delta = None + self._timeout = int(timeout) if timeout else None + + def _timeout_handler(self, *args): + raise exceptions.TimerTimeout(timeout=self._timeout) def __enter__(self): self.start = datetime.datetime.now() + if self._timeout: + signal.signal(signal.SIGALRM, self._timeout_handler) + signal.alarm(self._timeout) return self def __exit__(self, *_): + if self._timeout: + signal.alarm(0) self.delta = datetime.datetime.now() - self.start def __getattr__(self, item): @@ -455,3 +473,22 @@ def open_relative_file(path, task_path): if e.errno == errno.ENOENT: return open(os.path.join(task_path, path)) raise + + +def wait_until_true(predicate, timeout=60, sleep=1, exception=None): + """Wait until callable predicate is evaluated as True + + :param predicate: (func) callable deciding whether waiting should continue + :param timeout: (int) timeout in seconds how long should function wait + :param sleep: (int) polling interval for results in seconds + :param exception: exception instance to raise on timeout. If None is passed + (default) then WaitTimeout exception is raised. + """ + try: + with Timer(timeout=timeout): + while not predicate(): + time.sleep(sleep) + except exceptions.TimerTimeout: + if exception and issubclass(exception, Exception): + raise exception # pylint: disable=raising-bad-type + raise exceptions.WaitTimeout diff --git a/yardstick/network_services/libs/ixia_libs/IxNet/IxNet.py b/yardstick/network_services/libs/ixia_libs/IxNet/IxNet.py index 70ce4ff03..c538ceeba 100644 --- a/yardstick/network_services/libs/ixia_libs/IxNet/IxNet.py +++ b/yardstick/network_services/libs/ixia_libs/IxNet/IxNet.py @@ -12,13 +12,12 @@ # See the License for the specific language governing permissions and # limitations under the License. -from __future__ import absolute_import -from __future__ import print_function -import sys import logging import re from itertools import product +import IxNetwork + log = logging.getLogger(__name__) @@ -135,7 +134,6 @@ class IxNextgen(object): port.append(port0) cfg = { - 'py_lib_path': tg_cfg["mgmt-interface"]["tg-config"]["py_lib_path"], 'machine': tg_cfg["mgmt-interface"]["ip"], 'port': tg_cfg["mgmt-interface"]["tg-config"]["tcl_port"], 'chassis': tg_cfg["mgmt-interface"]["tg-config"]["ixchassis"], @@ -186,7 +184,7 @@ class IxNextgen(object): self.set_random_ip_multi_attribute(ip, seeds[1], fixed_bits, random_mask, l3_count) def add_ip_header(self, params, version): - for it, ep, i in self.iter_over_get_lists('/traffic', 'trafficItem', "configElement", 1): + for _, ep, i in self.iter_over_get_lists('/traffic', 'trafficItem', "configElement", 1): iter1 = (v['outer_l3'] for v in params.values() if str(v['id']) == str(i)) try: l3 = next(iter1, {}) @@ -194,21 +192,13 @@ class IxNextgen(object): except (KeyError, IndexError): continue - for ip, ip_bits, _ in self.iter_over_get_lists(ep, 'stack', 'field'): + for _, ip_bits, _ in self.iter_over_get_lists(ep, 'stack', 'field'): self.set_random_ip_multi_attributes(ip_bits, version, seeds, l3) self.ixnet.commit() def _connect(self, tg_cfg): self._cfg = self.get_config(tg_cfg) - - sys.path.append(self._cfg["py_lib_path"]) - # Import IxNetwork after getting ixia lib path - try: - import IxNetwork - except ImportError: - raise - self.ixnet = IxNetwork.IxNet() machine = self._cfg['machine'] @@ -292,7 +282,7 @@ class IxNextgen(object): self.update_ether_multi_attribute(ether, str(l2.get('srcmac', "00:00:00:00:00:01"))) def ix_update_ether(self, params): - for ti, ep, index in self.iter_over_get_lists('/traffic', 'trafficItem', + for _, ep, index in self.iter_over_get_lists('/traffic', 'trafficItem', "configElement", 1): iter1 = (v['outer_l2'] for v in params.values() if str(v['id']) == str(index)) try: @@ -300,7 +290,7 @@ class IxNextgen(object): except KeyError: continue - for ip, ether, _ in self.iter_over_get_lists(ep, 'stack', 'field'): + for _, ether, _ in self.iter_over_get_lists(ep, 'stack', 'field'): self.update_ether_multi_attributes(ether, l2) self.ixnet.commit() diff --git a/yardstick/network_services/nfvi/resource.py b/yardstick/network_services/nfvi/resource.py index dc5c46a86..0c0bf223a 100644 --- a/yardstick/network_services/nfvi/resource.py +++ b/yardstick/network_services/nfvi/resource.py @@ -27,6 +27,7 @@ from oslo_config import cfg from oslo_utils.encodeutils import safe_decode from yardstick import ssh +from yardstick.common.exceptions import ResourceCommandError from yardstick.common.task_template import finalize_for_yaml from yardstick.common.utils import validate_non_string_sequence from yardstick.network_services.nfvi.collectd import AmqpConsumer @@ -249,45 +250,46 @@ class ResourceProfile(object): if status != 0: LOG.error("cannot find OVS socket %s", socket_path) + def _start_rabbitmq(self, connection): + # Reset amqp queue + LOG.debug("reset and setup amqp to collect data from collectd") + # ensure collectd.conf.d exists to avoid error/warning + cmd_list = ["sudo mkdir -p /etc/collectd/collectd.conf.d", + "sudo service rabbitmq-server restart", + "sudo rabbitmqctl stop_app", + "sudo rabbitmqctl reset", + "sudo rabbitmqctl start_app", + "sudo rabbitmqctl add_user admin admin", + "sudo rabbitmqctl authenticate_user admin admin", + "sudo rabbitmqctl set_permissions -p / admin '.*' '.*' '.*'" + ] + for cmd in cmd_list: + exit_status, stdout, stderr = connection.execute(cmd) + if exit_status != 0: + raise ResourceCommandError(command=cmd, stderr=stderr) + + # check stdout for "sudo rabbitmqctl status" command + cmd = "sudo rabbitmqctl status" + _, stdout, stderr = connection.execute(cmd) + if not re.search("RabbitMQ", stdout): + LOG.error("rabbitmqctl status don't have RabbitMQ in running apps") + raise ResourceCommandError(command=cmd, stderr=stderr) + def _start_collectd(self, connection, bin_path): LOG.debug("Starting collectd to collect NFVi stats") - connection.execute('sudo pkill -x -9 collectd') collectd_path = os.path.join(bin_path, "collectd", "sbin", "collectd") config_file_path = os.path.join(bin_path, "collectd", "etc") + self._prepare_collectd_conf(config_file_path) + + connection.execute('sudo pkill -x -9 collectd') exit_status = connection.execute("which %s > /dev/null 2>&1" % collectd_path)[0] if exit_status != 0: LOG.warning("%s is not present disabling", collectd_path) - # disable auto-provisioning because it requires Internet access - # collectd_installer = os.path.join(bin_path, "collectd.sh") - # provision_tool(connection, collectd) - # http_proxy = os.environ.get('http_proxy', '') - # https_proxy = os.environ.get('https_proxy', '') - # connection.execute("sudo %s '%s' '%s'" % ( - # collectd_installer, http_proxy, https_proxy)) return if "ovs_stats" in self.plugins: self._setup_ovs_stats(connection) LOG.debug("Starting collectd to collect NFVi stats") - # ensure collectd.conf.d exists to avoid error/warning - connection.execute("sudo mkdir -p /etc/collectd/collectd.conf.d") - self._prepare_collectd_conf(config_file_path) - - # Reset amqp queue - LOG.debug("reset and setup amqp to collect data from collectd") - connection.execute("sudo rm -rf /var/lib/rabbitmq/mnesia/rabbit*") - connection.execute("sudo service rabbitmq-server start") - connection.execute("sudo rabbitmqctl stop_app") - connection.execute("sudo rabbitmqctl reset") - connection.execute("sudo rabbitmqctl start_app") - connection.execute("sudo service rabbitmq-server restart") - - LOG.debug("Creating admin user for rabbitmq in order to collect data from collectd") - connection.execute("sudo rabbitmqctl delete_user guest") - connection.execute("sudo rabbitmqctl add_user admin admin") - connection.execute("sudo rabbitmqctl authenticate_user admin admin") - connection.execute("sudo rabbitmqctl set_permissions -p / admin '.*' '.*' '.*'") - LOG.debug("Start collectd service..... %s second timeout", self.timeout) # intel_pmu plug requires large numbers of files open, so try to set # ulimit -n to a large value @@ -299,9 +301,10 @@ class ResourceProfile(object): """ Start system agent for NFVi collection on host """ if self.enable: try: + self._start_rabbitmq(self.connection) self._start_collectd(self.connection, bin_path) - except Exception: - LOG.exception("Exception during collectd start") + except ResourceCommandError as e: + LOG.exception("Exception during collectd and rabbitmq start: %s", str(e)) raise def start(self): diff --git a/yardstick/network_services/vnf_generic/vnf/sample_vnf.py b/yardstick/network_services/vnf_generic/vnf/sample_vnf.py index addbd9aa4..d8b9625fb 100644 --- a/yardstick/network_services/vnf_generic/vnf/sample_vnf.py +++ b/yardstick/network_services/vnf_generic/vnf/sample_vnf.py @@ -35,7 +35,6 @@ from yardstick.common import utils from yardstick.network_services import constants from yardstick.network_services.helpers.dpdkbindnic_helper import DpdkBindHelper, DpdkNode from yardstick.network_services.helpers.samplevnf_helper import MultiPortConfig -from yardstick.network_services.helpers.samplevnf_helper import PortPairs from yardstick.network_services.nfvi.resource import ResourceProfile from yardstick.network_services.utils import get_nsb_option from yardstick.network_services.vnf_generic.vnf.base import GenericTrafficGen @@ -79,7 +78,6 @@ class DpdkVnfSetupEnvHelper(SetupEnvHelper): APP_NAME = 'DpdkVnf' FIND_NET_CMD = "find /sys/class/net -lname '*{}*' -printf '%f'" NR_HUGEPAGES_PATH = '/proc/sys/vm/nr_hugepages' - HUGEPAGES_KB = 1024 * 1024 * 16 @staticmethod def _update_packet_type(ip_pipeline_cfg, traffic_options): @@ -118,7 +116,8 @@ class DpdkVnfSetupEnvHelper(SetupEnvHelper): def _setup_hugepages(self): meminfo = utils.read_meminfo(self.ssh_helper) hp_size_kb = int(meminfo['Hugepagesize']) - nr_hugepages = int(abs(self.HUGEPAGES_KB / hp_size_kb)) + hugepages_gb = self.scenario_helper.all_options.get('hugepages_gb', 16) + nr_hugepages = int(abs(hugepages_gb * 1024 * 1024 / hp_size_kb)) self.ssh_helper.execute('echo %s | sudo tee %s' % (nr_hugepages, self.NR_HUGEPAGES_PATH)) hp = six.BytesIO() @@ -657,49 +656,6 @@ class SampleVNF(GenericVNF): self.vnf_port_pairs = None self._vnf_process = None - def _build_ports(self): - self._port_pairs = PortPairs(self.vnfd_helper.interfaces) - self.networks = self._port_pairs.networks - self.uplink_ports = self.vnfd_helper.port_nums(self._port_pairs.uplink_ports) - self.downlink_ports = self.vnfd_helper.port_nums(self._port_pairs.downlink_ports) - self.my_ports = self.vnfd_helper.port_nums(self._port_pairs.all_ports) - - def _get_route_data(self, route_index, route_type): - route_iter = iter(self.vnfd_helper.vdu0.get('nd_route_tbl', [])) - for _ in range(route_index): - next(route_iter, '') - return next(route_iter, {}).get(route_type, '') - - def _get_port0localip6(self): - return_value = self._get_route_data(0, 'network') - LOG.info("_get_port0localip6 : %s", return_value) - return return_value - - def _get_port1localip6(self): - return_value = self._get_route_data(1, 'network') - LOG.info("_get_port1localip6 : %s", return_value) - return return_value - - def _get_port0prefixlen6(self): - return_value = self._get_route_data(0, 'netmask') - LOG.info("_get_port0prefixlen6 : %s", return_value) - return return_value - - def _get_port1prefixlen6(self): - return_value = self._get_route_data(1, 'netmask') - LOG.info("_get_port1prefixlen6 : %s", return_value) - return return_value - - def _get_port0gateway6(self): - return_value = self._get_route_data(0, 'network') - LOG.info("_get_port0gateway6 : %s", return_value) - return return_value - - def _get_port1gateway6(self): - return_value = self._get_route_data(1, 'network') - LOG.info("_get_port1gateway6 : %s", return_value) - return return_value - def _start_vnf(self): self.queue_wrapper = QueueFileWrapper(self.q_in, self.q_out, self.VNF_PROMPT) name = "{}-{}-{}".format(self.name, self.APP_NAME, os.getpid()) diff --git a/yardstick/orchestrator/heat.py b/yardstick/orchestrator/heat.py index d69f86044..e0c0db262 100644 --- a/yardstick/orchestrator/heat.py +++ b/yardstick/orchestrator/heat.py @@ -15,18 +15,20 @@ import datetime import getpass import logging import pkg_resources +import pprint import socket import tempfile import time from oslo_serialization import jsonutils from oslo_utils import encodeutils -import shade +from shade._heat import event_utils -import yardstick.common.openstack_utils as op_utils +from yardstick.common import constants as consts from yardstick.common import exceptions from yardstick.common import template_format -from yardstick.common import constants as consts +from yardstick.common import openstack_utils as op_utils + log = logging.getLogger(__name__) @@ -39,10 +41,11 @@ _DEPLOYED_STACKS = {} class HeatStack(object): """Represents a Heat stack (deployed template) """ - def __init__(self, name): + def __init__(self, name, os_cloud_config=None): self.name = name self.outputs = {} - self._cloud = shade.openstack_cloud() + os_cloud_config = {} if not os_cloud_config else os_cloud_config + self._cloud = op_utils.get_shade_client(**os_cloud_config) self._stack = None def _update_stack_tracking(self): @@ -63,6 +66,10 @@ class HeatStack(object): self._update_stack_tracking() + def get_failures(self): + return event_utils.get_events(self._cloud, self._stack.id, + event_args={'resource_status': 'FAILED'}) + def get(self): """Retrieves an existing stack from the target cloud @@ -146,10 +153,12 @@ name (i.e. %s). # short hand for resources part of template self.resources = self._template['resources'] - def __init__(self, name, template_file=None, heat_parameters=None): + def __init__(self, name, template_file=None, heat_parameters=None, + os_cloud_config=None): self.name = name self.keystone_client = None self.heat_parameters = {} + self._os_cloud_config = {} if not os_cloud_config else os_cloud_config # heat_parameters is passed to heat in stack create, empty dict when # yardstick creates the template (no get_param in resources part) @@ -616,7 +625,7 @@ name (i.e. %s). log.info("Creating stack '%s' START", self.name) start_time = time.time() - stack = HeatStack(self.name) + stack = HeatStack(self.name, os_cloud_config=self._os_cloud_config) stack.create(self._template, self.heat_parameters, block, timeout) if not block: @@ -625,6 +634,9 @@ name (i.e. %s). return stack if stack.status != self.HEAT_STATUS_COMPLETE: + for event in stack.get_failures(): + log.error("%s", event.resource_status_reason) + log.error(pprint.pformat(self._template)) raise exceptions.HeatTemplateError(stack_name=self.name) log.info("Creating stack '%s' DONE in %d secs", diff --git a/yardstick/tests/functional/common/messaging/__init__.py b/yardstick/tests/functional/common/messaging/__init__.py new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/yardstick/tests/functional/common/messaging/__init__.py diff --git a/yardstick/tests/functional/common/messaging/test_messaging.py b/yardstick/tests/functional/common/messaging/test_messaging.py new file mode 100644 index 000000000..99874343b --- /dev/null +++ b/yardstick/tests/functional/common/messaging/test_messaging.py @@ -0,0 +1,99 @@ +# Copyright (c) 2018 Intel Corporation +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import multiprocessing +import time + +from yardstick.common.messaging import consumer +from yardstick.common.messaging import payloads +from yardstick.common.messaging import producer +from yardstick.tests.functional import base + + +TOPIC = 'topic_MQ' +METHOD_INFO = 'info' + + +class DummyPayload(payloads.Payload): + REQUIRED_FIELDS = {'version', 'data'} + + +class DummyEndpoint(consumer.NotificationHandler): + + def info(self, ctxt, **kwargs): + if ctxt['pid'] in self._ctx_pids: + self._queue.put('ID {}, data: {}, pid: {}'.format( + self._id, kwargs['data'], ctxt['pid'])) + + +class DummyConsumer(consumer.MessagingConsumer): + + def __init__(self, _id, ctx_pids, queue): + self._id = _id + endpoints = [DummyEndpoint(_id, ctx_pids, queue)] + super(DummyConsumer, self).__init__(TOPIC, ctx_pids, endpoints) + + +class DummyProducer(producer.MessagingProducer): + pass + + +def _run_consumer(_id, ctx_pids, queue): + _consumer = DummyConsumer(_id, ctx_pids, queue) + _consumer.start_rpc_server() + _consumer.wait() + + +class MessagingTestCase(base.BaseFunctionalTestCase): + + @staticmethod + def _terminate_consumers(num_consumers, processes): + for i in range(num_consumers): + processes[i].terminate() + + def test_run_five_consumers(self): + output_queue = multiprocessing.Queue() + num_consumers = 10 + ctx_1 = 100001 + ctx_2 = 100002 + producers = [DummyProducer(TOPIC, pid=ctx_1), + DummyProducer(TOPIC, pid=ctx_2)] + + processes = [] + for i in range(num_consumers): + processes.append(multiprocessing.Process( + name='consumer_{}'.format(i), + target=_run_consumer, + args=(i, [ctx_1, ctx_2], output_queue))) + processes[i].start() + self.addCleanup(self._terminate_consumers, num_consumers, processes) + + time.sleep(2) # Let consumers to create the listeners + for producer in producers: + for message in ['message 0', 'message 1']: + producer.send_message(METHOD_INFO, + DummyPayload(version=1, data=message)) + + time.sleep(2) # Let consumers attend the calls + output = [] + while not output_queue.empty(): + output.append(output_queue.get(True, 1)) + + self.assertEqual(num_consumers * 4, len(output)) + msg_template = 'ID {}, data: {}, pid: {}' + for i in range(num_consumers): + for ctx in [ctx_1, ctx_2]: + for message in ['message 0', 'message 1']: + msg = msg_template.format(i, message, ctx) + self.assertIn(msg, output) diff --git a/yardstick/tests/integration/dummy-scenario-heat-context.yaml b/yardstick/tests/integration/dummy-scenario-heat-context.yaml new file mode 100644 index 000000000..45a39951a --- /dev/null +++ b/yardstick/tests/integration/dummy-scenario-heat-context.yaml @@ -0,0 +1,38 @@ +############################################################################## +# Copyright (c) 2018 Intel +# +# 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 +############################################################################## +{% set context_name = context_name or "demo" %} +--- +# Sample Heat context config with Dummy context + +schema: "yardstick:task:0.1" + +scenarios: +- + type: Dummy + + runner: + type: Duration + duration: 5 + interval: 1 + +context: + name: {{ context_name }} + image: yardstick-image + flavor: yardstick-flavor + user: ubuntu + + servers: + athena: + name: athena + ares: + name: ares + + networks: + test: + name: test diff --git a/yardstick/tests/unit/apiserver/resources/v1/__init__.py b/yardstick/tests/unit/apiserver/resources/v1/__init__.py new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/yardstick/tests/unit/apiserver/resources/v1/__init__.py diff --git a/yardstick/tests/unit/apiserver/resources/v1/test_testsuites.py b/yardstick/tests/unit/apiserver/resources/v1/test_testsuites.py new file mode 100644 index 000000000..85c045f44 --- /dev/null +++ b/yardstick/tests/unit/apiserver/resources/v1/test_testsuites.py @@ -0,0 +1,35 @@ +############################################################################## +# Copyright (c) 2018 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 mock + +import unittest + +from yardstick.tests.unit.apiserver import APITestCase +from api.utils.thread import TaskThread + + +class TestsuiteTestCase(APITestCase): + + def test_run_test_suite(self): + if self.app is None: + unittest.skip('host config error') + return + + TaskThread.start = mock.MagicMock() + + url = 'yardstick/testsuites/action' + data = { + 'action': 'run_test_suite', + 'args': { + 'opts': {}, + 'testsuite': 'opnfv_smoke' + } + } + resp = self._post(url, data) + self.assertEqual(resp.get('status'), 1) diff --git a/yardstick/tests/unit/apiserver/resources/v2/__init__.py b/yardstick/tests/unit/apiserver/resources/v2/__init__.py new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/yardstick/tests/unit/apiserver/resources/v2/__init__.py diff --git a/yardstick/tests/unit/apiserver/resources/v2/test_images.py b/yardstick/tests/unit/apiserver/resources/v2/test_images.py new file mode 100644 index 000000000..ab131eec5 --- /dev/null +++ b/yardstick/tests/unit/apiserver/resources/v2/test_images.py @@ -0,0 +1,46 @@ +############################################################################## +# Copyright (c) 2017 Huawei Technologies Co.,Ltd. +# +# 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 mock + +import unittest + +from yardstick.tests.unit.apiserver import APITestCase +from api.resources.v2.images import format_image_info + + +class V2ImagesTestCase(APITestCase): + @mock.patch('yardstick.common.openstack_utils.list_images') + @mock.patch('yardstick.common.utils.source_env') + def test_get(self, _, mock_list_images): + if self.app is None: + unittest.skip('host config error') + return + + single_image = mock.MagicMock() + single_image.name = 'yardstick-image' + single_image.size = 16384 + single_image.status = 'active' + single_image.updated_at = '2018-04-08' + + mock_list_images.return_value = [single_image] + url = 'api/v2/yardstick/images' + resp = self._get(url) + self.assertEqual(resp.get('status'), 1) + + +class FormatImageInfoTestCase(unittest.TestCase): + def test_format_image_info(self): + image = mock.MagicMock() + image.name = 'yardstick-image' + image.size = 1048576 + image.status = 'active' + image.updated_at = '2018-04-08' + + image_dict = format_image_info(image) + self.assertEqual(image_dict.get('size'), 1) diff --git a/yardstick/tests/unit/benchmark/contexts/standalone/test_model.py b/yardstick/tests/unit/benchmark/contexts/standalone/test_model.py index 18ea3c4e6..72e684a68 100644 --- a/yardstick/tests/unit/benchmark/contexts/standalone/test_model.py +++ b/yardstick/tests/unit/benchmark/contexts/standalone/test_model.py @@ -14,11 +14,16 @@ import copy import os -import unittest -import mock +import uuid +import mock +import unittest from xml.etree import ElementTree + +from yardstick import ssh from yardstick.benchmark.contexts.standalone import model +from yardstick.common import exceptions +from yardstick import constants from yardstick.network_services import utils @@ -38,22 +43,19 @@ XML_SAMPLE_INTERFACE = """<?xml version="1.0"?> </domain> """ + class ModelLibvirtTestCase(unittest.TestCase): def setUp(self): - self.xml = ElementTree.ElementTree( - element=ElementTree.fromstring(XML_SAMPLE)) self.pci_address_str = '0001:04:03.2' self.pci_address = utils.PciAddress(self.pci_address_str) self.mac = '00:00:00:00:00:01' - self._mock_write_xml = mock.patch.object(ElementTree.ElementTree, - 'write') - self.mock_write_xml = self._mock_write_xml.start() - + self._mock_ssh = mock.Mock() + self.mock_ssh = self._mock_ssh.start() self.addCleanup(self._cleanup) def _cleanup(self): - self._mock_write_xml.stop() + self._mock_ssh.stop() # TODO: Remove mocking of yardstick.ssh.SSH (here and elsewhere) # In this case, we are mocking a param to be passed into other methods @@ -67,20 +69,31 @@ class ModelLibvirtTestCase(unittest.TestCase): model.Libvirt.check_if_vm_exists_and_delete("vm_0", ssh_mock) def test_virsh_create_vm(self): - with mock.patch("yardstick.ssh.SSH") as ssh: - ssh_mock = mock.Mock(autospec=ssh.SSH) - ssh_mock.execute = mock.Mock(return_value=(0, "a", "")) - ssh.return_value = ssh_mock - # NOTE(ralonsoh): this test doesn't cover function execution. - model.Libvirt.virsh_create_vm(ssh_mock, "vm_0") + self.mock_ssh.execute = mock.Mock(return_value=(0, 0, 0)) + model.Libvirt.virsh_create_vm(self.mock_ssh, 'vm_0') + self.mock_ssh.execute.assert_called_once_with('virsh create vm_0') + + def test_virsh_create_vm_error(self): + self.mock_ssh.execute = mock.Mock(return_value=(1, 0, 'error_create')) + with self.assertRaises(exceptions.LibvirtCreateError) as exc: + model.Libvirt.virsh_create_vm(self.mock_ssh, 'vm_0') + self.assertEqual('Error creating the virtual machine. Error: ' + 'error_create.', str(exc.exception)) + self.mock_ssh.execute.assert_called_once_with('virsh create vm_0') def test_virsh_destroy_vm(self): - with mock.patch("yardstick.ssh.SSH") as ssh: - ssh_mock = mock.Mock(autospec=ssh.SSH) - ssh_mock.execute = mock.Mock(return_value=(0, "a", "")) - ssh.return_value = ssh_mock - # NOTE(ralonsoh): this test doesn't cover function execution. - model.Libvirt.virsh_destroy_vm("vm_0", ssh_mock) + self.mock_ssh.execute = mock.Mock(return_value=(0, 0, 0)) + model.Libvirt.virsh_destroy_vm('vm_0', self.mock_ssh) + self.mock_ssh.execute.assert_called_once_with('virsh destroy vm_0') + + @mock.patch.object(model, 'LOG') + def test_virsh_destroy_vm_error(self, mock_logger): + self.mock_ssh.execute = mock.Mock(return_value=(1, 0, 'error_destroy')) + mock_logger.warning = mock.Mock() + model.Libvirt.virsh_destroy_vm('vm_0', self.mock_ssh) + mock_logger.warning.assert_called_once_with( + 'Error destroying VM %s. Error: %s', 'vm_0', 'error_destroy') + self.mock_ssh.execute.assert_called_once_with('virsh destroy vm_0') def test_add_interface_address(self): xml = ElementTree.ElementTree( @@ -98,101 +111,164 @@ class ModelLibvirtTestCase(unittest.TestCase): result.get('function')) def test_add_ovs_interfaces(self): - xml_input = mock.Mock() - with mock.patch.object(ElementTree, 'parse', return_value=self.xml) \ - as mock_parse: - xml = copy.deepcopy(self.xml) - mock_parse.return_value = xml - model.Libvirt.add_ovs_interface( - '/usr/local', 0, self.pci_address_str, self.mac, xml_input) - mock_parse.assert_called_once_with(xml_input) - self.mock_write_xml.assert_called_once_with(xml_input) - interface = xml.find('devices').find('interface') - self.assertEqual('vhostuser', interface.get('type')) - mac = interface.find('mac') - self.assertEqual(self.mac, mac.get('address')) - source = interface.find('source') - self.assertEqual('unix', source.get('type')) - self.assertEqual('/usr/local/var/run/openvswitch/dpdkvhostuser0', - source.get('path')) - self.assertEqual('client', source.get('mode')) - _model = interface.find('model') - self.assertEqual('virtio', _model.get('type')) - driver = interface.find('driver') - self.assertEqual('4', driver.get('queues')) - host = driver.find('host') - self.assertEqual('off', host.get('mrg_rxbuf')) - self.assertIsNotNone(interface.find('address')) + xml_input = copy.deepcopy(XML_SAMPLE) + xml_output = model.Libvirt.add_ovs_interface( + '/usr/local', 0, self.pci_address_str, self.mac, xml_input) + + root = ElementTree.fromstring(xml_output) + et_out = ElementTree.ElementTree(element=root) + interface = et_out.find('devices').find('interface') + self.assertEqual('vhostuser', interface.get('type')) + mac = interface.find('mac') + self.assertEqual(self.mac, mac.get('address')) + source = interface.find('source') + self.assertEqual('unix', source.get('type')) + self.assertEqual('/usr/local/var/run/openvswitch/dpdkvhostuser0', + source.get('path')) + self.assertEqual('client', source.get('mode')) + _model = interface.find('model') + self.assertEqual('virtio', _model.get('type')) + driver = interface.find('driver') + self.assertEqual('4', driver.get('queues')) + host = driver.find('host') + self.assertEqual('off', host.get('mrg_rxbuf')) + self.assertIsNotNone(interface.find('address')) def test_add_sriov_interfaces(self): - xml_input = mock.Mock() - with mock.patch.object(ElementTree, 'parse', return_value=self.xml) \ - as mock_parse: - xml = copy.deepcopy(self.xml) - mock_parse.return_value = xml - vm_pci = '0001:05:04.2' - model.Libvirt.add_sriov_interfaces( - vm_pci, self.pci_address_str, self.mac, xml_input) - mock_parse.assert_called_once_with(xml_input) - self.mock_write_xml.assert_called_once_with(xml_input) - interface = xml.find('devices').find('interface') - self.assertEqual('yes', interface.get('managed')) - self.assertEqual('hostdev', interface.get('type')) - mac = interface.find('mac') - self.assertEqual(self.mac, mac.get('address')) - source = interface.find('source') - source_address = source.find('address') - self.assertIsNotNone(source.find('address')) - - self.assertEqual('pci', source_address.get('type')) - self.assertEqual('0x' + self.pci_address_str.split(':')[0], - source_address.get('domain')) - self.assertEqual('0x' + self.pci_address_str.split(':')[1], - source_address.get('bus')) - self.assertEqual('0x' + self.pci_address_str.split(':')[2].split('.')[0], - source_address.get('slot')) - self.assertEqual('0x' + self.pci_address_str.split(':')[2].split('.')[1], - source_address.get('function')) - - interface_address = interface.find('address') - self.assertEqual('pci', interface_address.get('type')) - self.assertEqual('0x' + vm_pci.split(':')[0], - interface_address.get('domain')) - self.assertEqual('0x' + vm_pci.split(':')[1], - interface_address.get('bus')) - self.assertEqual('0x' + vm_pci.split(':')[2].split('.')[0], - interface_address.get('slot')) - self.assertEqual('0x' + vm_pci.split(':')[2].split('.')[1], - interface_address.get('function')) + xml_input = copy.deepcopy(XML_SAMPLE) + vm_pci = '0001:05:04.2' + xml_output = model.Libvirt.add_sriov_interfaces( + vm_pci, self.pci_address_str, self.mac, xml_input) + root = ElementTree.fromstring(xml_output) + et_out = ElementTree.ElementTree(element=root) + interface = et_out.find('devices').find('interface') + self.assertEqual('yes', interface.get('managed')) + self.assertEqual('hostdev', interface.get('type')) + mac = interface.find('mac') + self.assertEqual(self.mac, mac.get('address')) + source = interface.find('source') + source_address = source.find('address') + self.assertIsNotNone(source.find('address')) + + self.assertEqual('pci', source_address.get('type')) + self.assertEqual('0x' + self.pci_address_str.split(':')[0], + source_address.get('domain')) + self.assertEqual('0x' + self.pci_address_str.split(':')[1], + source_address.get('bus')) + self.assertEqual('0x' + self.pci_address_str.split(':')[2].split('.')[0], + source_address.get('slot')) + self.assertEqual('0x' + self.pci_address_str.split(':')[2].split('.')[1], + source_address.get('function')) + + interface_address = interface.find('address') + self.assertEqual('pci', interface_address.get('type')) + self.assertEqual('0x' + vm_pci.split(':')[0], + interface_address.get('domain')) + self.assertEqual('0x' + vm_pci.split(':')[1], + interface_address.get('bus')) + self.assertEqual('0x' + vm_pci.split(':')[2].split('.')[0], + interface_address.get('slot')) + self.assertEqual('0x' + vm_pci.split(':')[2].split('.')[1], + interface_address.get('function')) def test_create_snapshot_qemu(self): - result = "/var/lib/libvirt/images/0.qcow2" - with mock.patch("yardstick.ssh.SSH") as ssh: - ssh_mock = mock.Mock(autospec=ssh.SSH) - ssh_mock.execute = \ - mock.Mock(return_value=(0, "a", "")) - ssh.return_value = ssh_mock - image = model.Libvirt.create_snapshot_qemu(ssh_mock, "0", "ubuntu.img") - self.assertEqual(image, result) - - @mock.patch.object(model.Libvirt, 'pin_vcpu_for_perf') - @mock.patch.object(model.Libvirt, 'create_snapshot_qemu') + self.mock_ssh.execute = mock.Mock(return_value=(0, 0, 0)) + index = 1 + vm_image = '/var/lib/libvirt/images/%s.qcow2' % index + base_image = '/tmp/base_image' + + model.Libvirt.create_snapshot_qemu(self.mock_ssh, index, base_image) + self.mock_ssh.execute.assert_has_calls([ + mock.call('rm -- "%s"' % vm_image), + mock.call('test -r %s' % base_image), + mock.call('qemu-img create -f qcow2 -o backing_file=%s %s' % + (base_image, vm_image)) + ]) + + @mock.patch.object(os.path, 'basename', return_value='base_image') + @mock.patch.object(os.path, 'normpath') + @mock.patch.object(os, 'access', return_value=True) + def test_create_snapshot_qemu_no_image_remote(self, + mock_os_access, mock_normpath, mock_basename): + self.mock_ssh.execute = mock.Mock( + side_effect=[(0, 0, 0), (1, 0, 0), (0, 0, 0), (0, 0, 0)]) + index = 1 + vm_image = '/var/lib/libvirt/images/%s.qcow2' % index + base_image = '/tmp/base_image' + mock_normpath.return_value = base_image + + model.Libvirt.create_snapshot_qemu(self.mock_ssh, index, base_image) + self.mock_ssh.execute.assert_has_calls([ + mock.call('rm -- "%s"' % vm_image), + mock.call('test -r %s' % base_image), + mock.call('mv -- "/tmp/%s" "%s"' % ('base_image', base_image)), + mock.call('qemu-img create -f qcow2 -o backing_file=%s %s' % + (base_image, vm_image)) + ]) + mock_os_access.assert_called_once_with(base_image, os.R_OK) + mock_normpath.assert_called_once_with(base_image) + mock_basename.assert_has_calls([mock.call(base_image)]) + self.mock_ssh.put_file.assert_called_once_with(base_image, + '/tmp/base_image') + + @mock.patch.object(os, 'access', return_value=False) + def test_create_snapshot_qemu_no_image_local(self, mock_os_access): + self.mock_ssh.execute = mock.Mock(side_effect=[(0, 0, 0), (1, 0, 0)]) + base_image = '/tmp/base_image' + + with self.assertRaises(exceptions.LibvirtQemuImageBaseImageNotPresent): + model.Libvirt.create_snapshot_qemu(self.mock_ssh, 3, base_image) + mock_os_access.assert_called_once_with(base_image, os.R_OK) + + def test_create_snapshot_qemu_error_qemuimg_command(self): + self.mock_ssh.execute = mock.Mock( + side_effect=[(0, 0, 0), (0, 0, 0), (1, 0, 0)]) + index = 1 + vm_image = '/var/lib/libvirt/images/%s.qcow2' % index + base_image = '/tmp/base_image' + + with self.assertRaises(exceptions.LibvirtQemuImageCreateError): + model.Libvirt.create_snapshot_qemu(self.mock_ssh, index, + base_image) + self.mock_ssh.execute.assert_has_calls([ + mock.call('rm -- "%s"' % vm_image), + mock.call('test -r %s' % base_image), + mock.call('qemu-img create -f qcow2 -o backing_file=%s %s' % + (base_image, vm_image)) + ]) + + @mock.patch.object(model.Libvirt, 'pin_vcpu_for_perf', return_value='4,5') + @mock.patch.object(model.Libvirt, 'create_snapshot_qemu', + return_value='qemu_image') def test_build_vm_xml(self, mock_create_snapshot_qemu, - *args): - # NOTE(ralonsoh): this test doesn't cover function execution. This test - # should also check mocked function calls. - cfg_file = 'test_config_file.cfg' - self.addCleanup(os.remove, cfg_file) - result = [4] - with mock.patch("yardstick.ssh.SSH") as ssh: - ssh_mock = mock.Mock(autospec=ssh.SSH) - ssh_mock.execute = \ - mock.Mock(return_value=(0, "a", "")) - ssh.return_value = ssh_mock - mock_create_snapshot_qemu.return_value = "0.img" - - status = model.Libvirt.build_vm_xml(ssh_mock, {}, cfg_file, 'vm_0', 0) - self.assertEqual(status[0], result[0]) + mock_pin_vcpu_for_perf): + extra_specs = {'hw:cpu_cores': '4', + 'hw:cpu_sockets': '3', + 'hw:cpu_threads': '2', + 'cputune': 'cool'} + flavor = {'ram': '1024', + 'extra_specs': extra_specs, + 'hw_socket': '1', + 'images': 'images'} + mac = model.StandaloneContextHelper.get_mac_address(0x00) + _uuid = uuid.uuid4() + connection = mock.Mock() + with mock.patch.object(model.StandaloneContextHelper, + 'get_mac_address', return_value=mac) as \ + mock_get_mac_address, \ + mock.patch.object(uuid, 'uuid4', return_value=_uuid): + xml_out, mac = model.Libvirt.build_vm_xml( + connection, flavor, 'vm_name', 100) + + xml_ref = model.VM_TEMPLATE.format(vm_name='vm_name', + random_uuid=_uuid, mac_addr=mac, memory='1024', vcpu='8', cpu='4', + numa_cpus='0-7', socket='3', threads='2', + vm_image='qemu_image', cpuset='4,5', cputune='cool') + self.assertEqual(xml_ref, xml_out) + mock_get_mac_address.assert_called_once_with(0x00) + mock_create_snapshot_qemu.assert_called_once_with( + connection, 100, 'images') + mock_pin_vcpu_for_perf.assert_called_once_with(connection, '1') # TODO: Edit this test to test state instead of output # update_interrupts_hugepages_perf does not return anything @@ -398,43 +474,80 @@ class ServerTestCase(unittest.TestCase): class OvsDeployTestCase(unittest.TestCase): - NETWORKS = { - 'mgmt': {'cidr': '152.16.100.10/24'}, - 'private_0': { - 'phy_port': "0000:05:00.0", - 'vpci': "0000:00:07.0", - 'driver': 'i40e', - 'mac': '', - 'cidr': '152.16.100.10/24', - 'gateway_ip': '152.16.100.20'}, - 'public_0': { - 'phy_port': "0000:05:00.1", - 'vpci': "0000:00:08.0", - 'driver': 'i40e', - 'mac': '', - 'cidr': '152.16.40.10/24', - 'gateway_ip': '152.16.100.20'} - } - - @mock.patch('yardstick.ssh.SSH') - def setUp(self, mock_ssh): - self.ovs_deploy = model.OvsDeploy(mock_ssh, '/tmp/dpdk-devbind.py', {}) + OVS_DETAILS = {'version': {'ovs': 'ovs_version', 'dpdk': 'dpdk_version'}} - def test___init__(self): - self.assertIsNotNone(self.ovs_deploy.connection) - - @mock.patch('yardstick.benchmark.contexts.standalone.model.os') - def test_prerequisite(self, *args): - # NOTE(ralonsoh): this test should check mocked function calls. - self.ovs_deploy.helper = mock.Mock() - self.assertIsNone(self.ovs_deploy.prerequisite()) - - @mock.patch('yardstick.benchmark.contexts.standalone.model.os') - def test_prerequisite_2(self, *args): - # NOTE(ralonsoh): this test should check mocked function calls. Rename - # this test properly. - self.ovs_deploy.helper = mock.Mock() - self.ovs_deploy.connection.execute = mock.Mock( - return_value=(1, '1.2.3.4 00:00:00:00:00:01', '')) - self.ovs_deploy.prerequisite = mock.Mock() - self.assertIsNone(self.ovs_deploy.ovs_deploy()) + def setUp(self): + self._mock_ssh = mock.patch.object(ssh, 'SSH') + self.mock_ssh = self._mock_ssh.start() + self.ovs_deploy = model.OvsDeploy(self.mock_ssh, + '/tmp/dpdk-devbind.py', + self.OVS_DETAILS) + self._mock_path_isfile = mock.patch.object(os.path, 'isfile') + self._mock_path_join = mock.patch.object(os.path, 'join') + self.mock_path_isfile = self._mock_path_isfile.start() + self.mock_path_join = self._mock_path_join.start() + + self.addCleanup(self._stop_mock) + + def _stop_mock(self): + self._mock_ssh.stop() + self._mock_path_isfile.stop() + self._mock_path_join.stop() + + @mock.patch.object(model.StandaloneContextHelper, 'install_req_libs') + def test_prerequisite(self, mock_install_req_libs): + pkgs = ["git", "build-essential", "pkg-config", "automake", + "autotools-dev", "libltdl-dev", "cmake", "libnuma-dev", + "libpcap-dev"] + self.ovs_deploy.prerequisite() + mock_install_req_libs.assert_called_once_with( + self.ovs_deploy.connection, pkgs) + + def test_ovs_deploy_no_file(self): + self.mock_path_isfile.return_value = False + mock_file = mock.Mock() + self.mock_path_join.return_value = mock_file + + self.ovs_deploy.ovs_deploy() + self.mock_path_isfile.assert_called_once_with(mock_file) + self.mock_path_join.assert_called_once_with( + constants.YARDSTICK_ROOT_PATH, + 'yardstick/resources/scripts/install/', + self.ovs_deploy.OVS_DEPLOY_SCRIPT) + + @mock.patch.object(os.environ, 'get', return_value='test_proxy') + def test_ovs_deploy(self, mock_env_get): + self.mock_path_isfile.return_value = True + mock_deploy_file = mock.Mock() + mock_remove_ovs_deploy = mock.Mock() + self.mock_path_join.side_effect = [mock_deploy_file, + mock_remove_ovs_deploy] + dpdk_version = self.OVS_DETAILS['version']['dpdk'] + ovs_version = self.OVS_DETAILS['version']['ovs'] + + with mock.patch.object(self.ovs_deploy.connection, 'put') as \ + mock_put, \ + mock.patch.object(self.ovs_deploy.connection, 'execute') as \ + mock_execute, \ + mock.patch.object(self.ovs_deploy, 'prerequisite'): + mock_execute.return_value = (0, 0, 0) + self.ovs_deploy.ovs_deploy() + + self.mock_path_isfile.assert_called_once_with(mock_deploy_file) + self.mock_path_join.assert_has_calls([ + mock.call(constants.YARDSTICK_ROOT_PATH, + 'yardstick/resources/scripts/install/', + self.ovs_deploy.OVS_DEPLOY_SCRIPT), + mock.call(self.ovs_deploy.bin_path, + self.ovs_deploy.OVS_DEPLOY_SCRIPT) + ]) + mock_put.assert_called_once_with(mock_deploy_file, + mock_remove_ovs_deploy) + cmd = ("sudo -E %(remote_ovs_deploy)s --ovs='%(ovs_version)s' " + "--dpdk='%(dpdk_version)s' -p='%(proxy)s'" % + {'remote_ovs_deploy': mock_remove_ovs_deploy, + 'ovs_version': ovs_version, + 'dpdk_version': dpdk_version, + 'proxy': 'test_proxy'}) + mock_execute.assert_called_once_with(cmd) + mock_env_get.assert_called_once_with('http_proxy', '') diff --git a/yardstick/tests/unit/benchmark/contexts/standalone/test_ovs_dpdk.py b/yardstick/tests/unit/benchmark/contexts/standalone/test_ovs_dpdk.py index 0223fd3ff..bc3bb73cd 100644 --- a/yardstick/tests/unit/benchmark/contexts/standalone/test_ovs_dpdk.py +++ b/yardstick/tests/unit/benchmark/contexts/standalone/test_ovs_dpdk.py @@ -12,12 +12,17 @@ # See the License for the specific language governing permissions and # limitations under the License. +import io import os import mock +import six import unittest +from yardstick.benchmark.contexts.standalone import model from yardstick.benchmark.contexts.standalone import ovs_dpdk +from yardstick.common import exceptions +from yardstick.network_services import utils class OvsDpdkContextTestCase(unittest.TestCase): @@ -27,7 +32,6 @@ class OvsDpdkContextTestCase(unittest.TestCase): NODES_DUPLICATE_SAMPLE = "nodes_duplicate_sample.yaml" NETWORKS = { - 'mgmt': {'cidr': '152.16.100.10/24'}, 'private_0': { 'phy_port': "0000:05:00.0", 'vpci': "0000:00:07.0", @@ -82,15 +86,43 @@ class OvsDpdkContextTestCase(unittest.TestCase): self.assertIsNone(self.ovs_dpdk.init(ATTRS)) def test_setup_ovs(self): - with mock.patch("yardstick.ssh.SSH") as ssh: - ssh_mock = mock.Mock(autospec=ssh.SSH) - ssh_mock.execute = \ - mock.Mock(return_value=(0, "a", "")) - ssh.return_value = ssh_mock - self.ovs_dpdk.connection = ssh_mock - self.ovs_dpdk.networks = self.NETWORKS - self.ovs_dpdk.ovs_properties = {} - self.assertIsNone(self.ovs_dpdk.setup_ovs()) + fake_path = '/fake_path' + fake_dpdk_nic_bind = 'dpdk_tool.py' + self.ovs_dpdk.ovs_properties = {'vpath': fake_path} + self.ovs_dpdk.dpdk_devbind = fake_dpdk_nic_bind + self.ovs_dpdk.networks = self.NETWORKS + self.ovs_dpdk.connection = mock.Mock() + self.ovs_dpdk.connection.execute = mock.Mock(return_value=(0, 0, 0)) + create_from = fake_path + '/etc/openvswitch/conf.db' + create_to = fake_path + '/share/openvswitch/vswitch.ovsschema' + cmd_list = [ + 'killall -r "ovs.*" -q | true', + 'mkdir -p {0}/etc/openvswitch'.format(fake_path), + 'mkdir -p {0}/var/run/openvswitch'.format(fake_path), + 'rm {0}/etc/openvswitch/conf.db | true'.format(fake_path), + 'ovsdb-tool create {0} {1}'.format(create_from, create_to), + 'modprobe vfio-pci', + 'chmod a+x /dev/vfio', + 'chmod 0666 /dev/vfio/*', + '{0} --force -b vfio-pci {1}'.format(fake_dpdk_nic_bind, + self.ovs_dpdk.networks['private_0']['phy_port']), + '{0} --force -b vfio-pci {1}'.format(fake_dpdk_nic_bind, + self.ovs_dpdk.networks['public_0']['phy_port']) + ] + calls = [mock.call(cmd, timeout=self.ovs_dpdk.CMD_TIMEOUT) + for cmd in cmd_list] + + self.ovs_dpdk.setup_ovs() + self.ovs_dpdk.connection.execute.assert_has_calls(calls, + any_order=True) + + def test_setup_ovs_exception(self): + self.ovs_dpdk.networks = self.NETWORKS + self.ovs_dpdk.connection = mock.Mock() + self.ovs_dpdk.connection.execute = mock.Mock(return_value=(1, 0, 0)) + + with self.assertRaises(exceptions.OVSSetupError): + self.ovs_dpdk.setup_ovs() def test_start_ovs_serverswitch(self): with mock.patch("yardstick.ssh.SSH") as ssh: @@ -129,34 +161,45 @@ class OvsDpdkContextTestCase(unittest.TestCase): self.ovs_dpdk.wait_for_vswitchd = 0 self.assertIsNone(self.ovs_dpdk.cleanup_ovs_dpdk_env()) - @mock.patch('yardstick.benchmark.contexts.standalone.model.OvsDeploy') - def test_check_ovs_dpdk_env(self, mock_ovs): - with mock.patch("yardstick.ssh.SSH") as ssh: - ssh_mock = mock.Mock(autospec=ssh.SSH) - ssh_mock.execute = \ - mock.Mock(return_value=(1, "a", "")) - ssh.return_value = ssh_mock - self.ovs_dpdk.connection = ssh_mock - self.ovs_dpdk.networks = self.NETWORKS - self.ovs_dpdk.ovs_properties = { - 'version': {'ovs': '2.7.0', 'dpdk': '16.11.1'} - } - self.ovs_dpdk.wait_for_vswitchd = 0 - self.ovs_dpdk.cleanup_ovs_dpdk_env = mock.Mock() - self.assertIsNone(self.ovs_dpdk.check_ovs_dpdk_env()) - self.ovs_dpdk.ovs_properties = { - 'version': {'ovs': '2.0.0'} - } - self.ovs_dpdk.wait_for_vswitchd = 0 - self.cleanup_ovs_dpdk_env = mock.Mock() - mock_ovs.deploy = mock.Mock() - # NOTE(elfoley): Check for a specific Exception - self.assertRaises(Exception, self.ovs_dpdk.check_ovs_dpdk_env) + @mock.patch.object(ovs_dpdk.OvsDpdkContext, '_check_hugepages') + @mock.patch.object(utils, 'get_nsb_option') + @mock.patch.object(model.OvsDeploy, 'ovs_deploy') + def test_check_ovs_dpdk_env(self, mock_ovs_deploy, mock_get_nsb_option, + mock_check_hugepages): + self.ovs_dpdk.connection = mock.Mock() + self.ovs_dpdk.connection.execute = mock.Mock( + return_value=(1, 0, 0)) + self.ovs_dpdk.networks = self.NETWORKS + self.ovs_dpdk.ovs_properties = { + 'version': {'ovs': '2.7.0', 'dpdk': '16.11.1'} + } + self.ovs_dpdk.wait_for_vswitchd = 0 + self.ovs_dpdk.cleanup_ovs_dpdk_env = mock.Mock() + mock_get_nsb_option.return_value = 'fake_path' + + self.ovs_dpdk.check_ovs_dpdk_env() + mock_ovs_deploy.assert_called_once() + mock_check_hugepages.assert_called_once() + mock_get_nsb_option.assert_called_once_with('bin_path') + + @mock.patch.object(ovs_dpdk.OvsDpdkContext, '_check_hugepages') + def test_check_ovs_dpdk_env_wrong_version(self, mock_check_hugepages): + self.ovs_dpdk.connection = mock.Mock() + self.ovs_dpdk.connection.execute = mock.Mock( + return_value=(1, 0, 0)) + self.ovs_dpdk.networks = self.NETWORKS + self.ovs_dpdk.ovs_properties = { + 'version': {'ovs': '0.0.1', 'dpdk': '9.8.7'} + } + self.ovs_dpdk.wait_for_vswitchd = 0 + self.ovs_dpdk.cleanup_ovs_dpdk_env = mock.Mock() - @mock.patch('yardstick.ssh.SSH') - def test_deploy(self, mock_ssh): - mock_ssh.execute.return_value = 0, "a", "" + with self.assertRaises(exceptions.OVSUnsupportedVersion): + self.ovs_dpdk.check_ovs_dpdk_env() + mock_check_hugepages.assert_called_once() + @mock.patch('yardstick.ssh.SSH') + def test_deploy(self, *args): self.ovs_dpdk.vm_deploy = False self.assertIsNone(self.ovs_dpdk.deploy()) @@ -174,21 +217,19 @@ class OvsDpdkContextTestCase(unittest.TestCase): # output. self.assertIsNone(self.ovs_dpdk.deploy()) - @mock.patch('yardstick.benchmark.contexts.standalone.model.Libvirt') - @mock.patch('yardstick.ssh.SSH') - def test_undeploy(self, mock_ssh, *args): - mock_ssh.execute.return_value = 0, "a", "" - - self.ovs_dpdk.vm_deploy = False - self.assertIsNone(self.ovs_dpdk.undeploy()) - + @mock.patch.object(model.Libvirt, 'check_if_vm_exists_and_delete') + def test_undeploy(self, mock_libvirt): self.ovs_dpdk.vm_deploy = True - self.ovs_dpdk.connection = mock_ssh + self.ovs_dpdk.connection = mock.Mock() self.ovs_dpdk.vm_names = ['vm_0', 'vm_1'] self.ovs_dpdk.drivers = ['vm_0', 'vm_1'] self.ovs_dpdk.cleanup_ovs_dpdk_env = mock.Mock() self.ovs_dpdk.networks = self.NETWORKS - self.assertIsNone(self.ovs_dpdk.undeploy()) + self.ovs_dpdk.undeploy() + mock_libvirt.assert_has_calls([ + mock.call(self.ovs_dpdk.vm_names[0], self.ovs_dpdk.connection), + mock.call(self.ovs_dpdk.vm_names[1], self.ovs_dpdk.connection) + ]) def _get_file_abspath(self, filename): curr_path = os.path.dirname(os.path.abspath(__file__)) @@ -310,34 +351,28 @@ class OvsDpdkContextTestCase(unittest.TestCase): self.ovs_dpdk.get_vf_datas = mock.Mock(return_value="") self.assertIsNone(self.ovs_dpdk.configure_nics_for_ovs_dpdk()) - @mock.patch('yardstick.benchmark.contexts.standalone.ovs_dpdk.Libvirt') - def test__enable_interfaces(self, *args): - with mock.patch("yardstick.ssh.SSH") as ssh: - ssh_mock = mock.Mock(autospec=ssh.SSH) - ssh_mock.execute = \ - mock.Mock(return_value=(0, "a", "")) - ssh.return_value = ssh_mock + @mock.patch.object(model.Libvirt, 'add_ovs_interface') + def test__enable_interfaces(self, mock_add_ovs_interface): self.ovs_dpdk.vm_deploy = True - self.ovs_dpdk.connection = ssh_mock + self.ovs_dpdk.connection = mock.Mock() self.ovs_dpdk.vm_names = ['vm_0', 'vm_1'] self.ovs_dpdk.drivers = [] self.ovs_dpdk.networks = self.NETWORKS + self.ovs_dpdk.ovs_properties = {'vpath': 'fake_path'} self.ovs_dpdk.get_vf_datas = mock.Mock(return_value="") - self.assertIsNone(self.ovs_dpdk._enable_interfaces( - 0, ["private_0"], 'test')) - - @mock.patch('yardstick.benchmark.contexts.standalone.model.Server') - @mock.patch('yardstick.benchmark.contexts.standalone.ovs_dpdk.Libvirt') - def test_setup_ovs_dpdk_context(self, mock_libvirt, *args): - with mock.patch("yardstick.ssh.SSH") as ssh: - ssh_mock = mock.Mock(autospec=ssh.SSH) - ssh_mock.execute = \ - mock.Mock(return_value=(0, "a", "")) - ssh_mock.put = \ - mock.Mock(return_value=(0, "a", "")) - ssh.return_value = ssh_mock + self.ovs_dpdk._enable_interfaces(0, ["private_0"], 'test') + mock_add_ovs_interface.assert_called_once_with( + 'fake_path', 0, self.NETWORKS['private_0']['vpci'], + self.NETWORKS['private_0']['mac'], 'test') + + @mock.patch.object(model.Libvirt, 'write_file') + @mock.patch.object(model.Libvirt, 'build_vm_xml') + @mock.patch.object(model.Libvirt, 'check_if_vm_exists_and_delete') + @mock.patch.object(model.Libvirt, 'virsh_create_vm') + def test_setup_ovs_dpdk_context(self, mock_create_vm, mock_check_if_exists, + mock_build_xml, mock_write_file): self.ovs_dpdk.vm_deploy = True - self.ovs_dpdk.connection = ssh_mock + self.ovs_dpdk.connection = mock.Mock() self.ovs_dpdk.vm_names = ['vm_0', 'vm_1'] self.ovs_dpdk.drivers = [] self.ovs_dpdk.servers = { @@ -353,11 +388,64 @@ class OvsDpdkContextTestCase(unittest.TestCase): self.ovs_dpdk.host_mgmt = {} self.ovs_dpdk.flavor = {} self.ovs_dpdk.configure_nics_for_ovs_dpdk = mock.Mock(return_value="") - mock_libvirt.build_vm_xml.return_value = [6, "00:00:00:00:00:01"] - self.ovs_dpdk._enable_interfaces = mock.Mock(return_value="") - mock_libvirt.virsh_create_vm.return_value = "" - mock_libvirt.pin_vcpu_for_perf.return_value = "" + xml_str = mock.Mock() + mock_build_xml.return_value = (xml_str, '00:00:00:00:00:01') + self.ovs_dpdk._enable_interfaces = mock.Mock(return_value=xml_str) + vnf_instance = mock.Mock() self.ovs_dpdk.vnf_node.generate_vnf_instance = mock.Mock( - return_value={}) - - self.assertIsNotNone(self.ovs_dpdk.setup_ovs_dpdk_context()) + return_value=vnf_instance) + + self.assertEqual([vnf_instance], + self.ovs_dpdk.setup_ovs_dpdk_context()) + mock_create_vm.assert_called_once_with( + self.ovs_dpdk.connection, '/tmp/vm_ovs_0.xml') + mock_check_if_exists.assert_called_once_with( + 'vm_0', self.ovs_dpdk.connection) + mock_build_xml.assert_called_once_with( + self.ovs_dpdk.connection, self.ovs_dpdk.vm_flavor, 'vm_0', 0) + mock_write_file.assert_called_once_with('/tmp/vm_ovs_0.xml', xml_str) + + @mock.patch.object(io, 'BytesIO') + def test__check_hugepages(self, mock_bytesio): + data = six.BytesIO('HugePages_Total: 20\n' + 'HugePages_Free: 20\n' + 'HugePages_Rsvd: 0\n' + 'HugePages_Surp: 0\n' + 'Hugepagesize: 1048576 kB'.encode()) + mock_bytesio.return_value = data + self.ovs_dpdk.connection = mock.Mock() + self.ovs_dpdk._check_hugepages() + + @mock.patch.object(io, 'BytesIO') + def test__check_hugepages_no_info(self, mock_bytesio): + data = six.BytesIO(''.encode()) + mock_bytesio.return_value = data + self.ovs_dpdk.connection = mock.Mock() + with self.assertRaises(exceptions.OVSHugepagesInfoError): + self.ovs_dpdk._check_hugepages() + + @mock.patch.object(io, 'BytesIO') + def test__check_hugepages_no_total_hp(self, mock_bytesio): + data = six.BytesIO('HugePages_Total: 0\n' + 'HugePages_Free: 0\n' + 'HugePages_Rsvd: 0\n' + 'HugePages_Surp: 0\n' + 'Hugepagesize: 1048576 kB'.encode()) + mock_bytesio.return_value = data + self.ovs_dpdk.connection = mock.Mock() + with self.assertRaises(exceptions.OVSHugepagesNotConfigured): + self.ovs_dpdk._check_hugepages() + + @mock.patch.object(io, 'BytesIO') + def test__check_hugepages_no_free_hp(self, mock_bytesio): + data = six.BytesIO('HugePages_Total: 20\n' + 'HugePages_Free: 0\n' + 'HugePages_Rsvd: 0\n' + 'HugePages_Surp: 0\n' + 'Hugepagesize: 1048576 kB'.encode()) + mock_bytesio.return_value = data + self.ovs_dpdk.connection = mock.Mock() + with self.assertRaises(exceptions.OVSHugepagesZeroFree) as exc: + self.ovs_dpdk._check_hugepages() + self.assertEqual('There are no HugePages free in this system. Total ' + 'HugePages configured: 20', exc.exception.msg) diff --git a/yardstick/tests/unit/benchmark/contexts/standalone/test_sriov.py b/yardstick/tests/unit/benchmark/contexts/standalone/test_sriov.py index f0953ef55..e70ab0ae8 100644 --- a/yardstick/tests/unit/benchmark/contexts/standalone/test_sriov.py +++ b/yardstick/tests/unit/benchmark/contexts/standalone/test_sriov.py @@ -18,6 +18,7 @@ import mock import unittest from yardstick import ssh +from yardstick.benchmark.contexts.standalone import model from yardstick.benchmark.contexts.standalone import sriov @@ -69,10 +70,11 @@ class SriovContextTestCase(unittest.TestCase): if self.sriov in self.sriov.list: self.sriov._delete_context() - @mock.patch('yardstick.benchmark.contexts.standalone.sriov.Libvirt') - @mock.patch('yardstick.benchmark.contexts.standalone.model.StandaloneContextHelper') - @mock.patch('yardstick.benchmark.contexts.standalone.model.Server') - def test___init__(self, mock_helper, mock_server, *args): + @mock.patch.object(model, 'StandaloneContextHelper') + @mock.patch.object(model, 'Libvirt') + @mock.patch.object(model, 'Server') + def test___init__(self, mock_helper, mock_libvirt, mock_server): + # pylint: disable=unused-argument # NOTE(ralonsoh): this test doesn't cover function execution. self.sriov.helper = mock_helper self.sriov.vnf_node = mock_server @@ -97,9 +99,11 @@ class SriovContextTestCase(unittest.TestCase): self.sriov.wait_for_vnfs_to_start = mock.Mock(return_value={}) self.assertIsNone(self.sriov.deploy()) - @mock.patch('yardstick.benchmark.contexts.standalone.sriov.Libvirt') @mock.patch.object(ssh, 'SSH', return_value=(0, "a", "")) - def test_undeploy(self, mock_ssh, *args): + @mock.patch.object(model, 'Libvirt') + def test_undeploy(self, mock_libvirt, mock_ssh): + # pylint: disable=unused-argument + # NOTE(ralonsoh): the pylint exception should be removed. self.sriov.vm_deploy = False self.assertIsNone(self.sriov.undeploy()) @@ -237,11 +241,11 @@ class SriovContextTestCase(unittest.TestCase): self.sriov._get_vf_data = mock.Mock(return_value="") self.assertIsNone(self.sriov.configure_nics_for_sriov()) - @mock.patch('yardstick.benchmark.contexts.standalone.sriov.Libvirt') - @mock.patch.object(ssh, 'SSH') - def test__enable_interfaces(self, mock_ssh, *args): - mock_ssh.return_value = 0, "a", "" - + @mock.patch.object(ssh, 'SSH', return_value=(0, "a", "")) + @mock.patch.object(model, 'Libvirt') + def test__enable_interfaces(self, mock_libvirt, mock_ssh): + # pylint: disable=unused-argument + # NOTE(ralonsoh): the pylint exception should be removed. self.sriov.vm_deploy = True self.sriov.connection = mock_ssh self.sriov.vm_names = ['vm_0', 'vm_1'] @@ -251,20 +255,12 @@ class SriovContextTestCase(unittest.TestCase): self.assertIsNone(self.sriov._enable_interfaces( 0, 0, ["private_0"], 'test')) - @mock.patch('yardstick.benchmark.contexts.standalone.model.Server') - @mock.patch('yardstick.benchmark.contexts.standalone.sriov.Libvirt') - def test_setup_sriov_context(self, mock_libvirt, *args): - with mock.patch("yardstick.ssh.SSH") as ssh: - ssh_mock = mock.Mock(autospec=ssh.SSH) - ssh_mock.execute = \ - mock.Mock(return_value=(0, "a", "")) - ssh_mock.put = \ - mock.Mock(return_value=(0, "a", "")) - ssh.return_value = ssh_mock - self.sriov.vm_deploy = True - self.sriov.connection = ssh_mock - self.sriov.vm_names = ['vm_0', 'vm_1'] - self.sriov.drivers = [] + @mock.patch.object(model.Libvirt, 'build_vm_xml') + @mock.patch.object(model.Libvirt, 'check_if_vm_exists_and_delete') + @mock.patch.object(model.Libvirt, 'write_file') + @mock.patch.object(model.Libvirt, 'virsh_create_vm') + def test_setup_sriov_context(self, mock_create_vm, mock_write_file, + mock_check, mock_build_vm_xml): self.sriov.servers = { 'vnf_0': { 'network_ports': { @@ -274,15 +270,31 @@ class SriovContextTestCase(unittest.TestCase): } } } - self.sriov.networks = self.NETWORKS - self.sriov.host_mgmt = {} - self.sriov.flavor = {} - self.sriov.configure_nics_for_sriov = mock.Mock(return_value="") - mock_libvirt.build_vm_xml = mock.Mock( - return_value=[6, "00:00:00:00:00:01"]) - self.sriov._enable_interfaces = mock.Mock(return_value="") - self.sriov.vnf_node.generate_vnf_instance = mock.Mock(return_value={}) - self.assertIsNotNone(self.sriov.setup_sriov_context()) + connection = mock.Mock() + self.sriov.connection = connection + self.sriov.host_mgmt = {'ip': '1.2.3.4'} + self.sriov.vm_flavor = 'flavor' + self.sriov.networks = 'networks' + self.sriov.configure_nics_for_sriov = mock.Mock() + cfg = '/tmp/vm_sriov_0.xml' + vm_name = 'vm_0' + xml_out = mock.Mock() + mock_build_vm_xml.return_value = (xml_out, '00:00:00:00:00:01') + + with mock.patch.object(self.sriov, 'vnf_node') as mock_vnf_node, \ + mock.patch.object(self.sriov, '_enable_interfaces'): + mock_vnf_node.generate_vnf_instance = mock.Mock( + return_value='node') + nodes_out = self.sriov.setup_sriov_context() + self.assertEqual(['node'], nodes_out) + mock_vnf_node.generate_vnf_instance.assert_called_once_with( + 'flavor', 'networks', '1.2.3.4', 'vnf_0', + self.sriov.servers['vnf_0'], '00:00:00:00:00:01') + mock_build_vm_xml.assert_called_once_with( + connection, 'flavor', vm_name, 0) + mock_create_vm.assert_called_once_with(connection, cfg) + mock_check.assert_called_once_with(vm_name, connection) + mock_write_file.assert_called_once_with(cfg, xml_out) def test__get_vf_data(self): with mock.patch("yardstick.ssh.SSH") as ssh: diff --git a/yardstick/tests/unit/benchmark/contexts/test_base.py b/yardstick/tests/unit/benchmark/contexts/test_base.py index 153c6a527..b19883479 100644 --- a/yardstick/tests/unit/benchmark/contexts/test_base.py +++ b/yardstick/tests/unit/benchmark/contexts/test_base.py @@ -25,6 +25,7 @@ class FlagsTestCase(unittest.TestCase): def test___init__(self): self.assertFalse(self.flags.no_setup) self.assertFalse(self.flags.no_teardown) + self.assertEqual({'verify': False}, self.flags.os_cloud_config) def test___init__with_flags(self): flags = base.Flags(no_setup=True) @@ -32,10 +33,12 @@ class FlagsTestCase(unittest.TestCase): self.assertFalse(flags.no_teardown) def test_parse(self): - self.flags.parse(no_setup=True, no_teardown="False") + self.flags.parse(no_setup=True, no_teardown='False', + os_cloud_config={'verify': True}) self.assertTrue(self.flags.no_setup) - self.assertEqual(self.flags.no_teardown, "False") + self.assertEqual('False', self.flags.no_teardown) + self.assertEqual({'verify': True}, self.flags.os_cloud_config) def test_parse_forbidden_flags(self): self.flags.parse(foo=42) diff --git a/yardstick/tests/unit/benchmark/contexts/test_heat.py b/yardstick/tests/unit/benchmark/contexts/test_heat.py index 625f97bf4..ebb1d69ba 100644 --- a/yardstick/tests/unit/benchmark/contexts/test_heat.py +++ b/yardstick/tests/unit/benchmark/contexts/test_heat.py @@ -229,12 +229,12 @@ class HeatContextTestCase(unittest.TestCase): self.assertRaises(y_exc.HeatTemplateError, self.test_context.deploy) - mock_path_exists.assert_called_once() + mock_path_exists.assert_called() mock_resources_template.assert_called_once() @mock.patch.object(os.path, 'exists', return_value=False) @mock.patch.object(ssh.SSH, 'gen_keys') - @mock.patch('yardstick.benchmark.contexts.heat.HeatTemplate') + @mock.patch.object(heat, 'HeatTemplate') def test_deploy(self, mock_template, mock_genkeys, mock_path_exists): self.test_context._name = 'foo' self.test_context._task_id = '1234567890' @@ -245,16 +245,17 @@ class HeatContextTestCase(unittest.TestCase): self.test_context.get_neutron_info = mock.MagicMock() self.test_context.deploy() - mock_template.assert_called_with('foo-12345678', - '/bar/baz/some-heat-file', - {'image': 'cirros'}) + mock_template.assert_called_with( + 'foo-12345678', template_file='/bar/baz/some-heat-file', + heat_parameters={'image': 'cirros'}, + os_cloud_config=self.test_context._flags.os_cloud_config) self.assertIsNotNone(self.test_context.stack) key_filename = ''.join( [consts.YARDSTICK_ROOT_PATH, 'yardstick/resources/files/yardstick_key-', self.test_context._name_task_id]) mock_genkeys.assert_called_once_with(key_filename) - mock_path_exists.assert_called_once_with(key_filename) + mock_path_exists.assert_any_call(key_filename) @mock.patch.object(heat, 'HeatTemplate') @mock.patch.object(os.path, 'exists', return_value=False) @@ -280,7 +281,7 @@ class HeatContextTestCase(unittest.TestCase): 'yardstick/resources/files/yardstick_key-', self.test_context._name]) mock_genkeys.assert_called_once_with(key_filename) - mock_path_exists.assert_called_once_with(key_filename) + mock_path_exists.assert_any_call(key_filename) @mock.patch.object(heat, 'HeatTemplate') @mock.patch.object(os.path, 'exists', return_value=False) @@ -296,7 +297,6 @@ class HeatContextTestCase(unittest.TestCase): self.test_context._flags.no_setup = True self.test_context.template_file = '/bar/baz/some-heat-file' self.test_context.get_neutron_info = mock.MagicMock() - self.test_context.deploy() mock_retrieve_stack.assert_called_once_with(self.test_context._name) @@ -306,7 +306,7 @@ class HeatContextTestCase(unittest.TestCase): 'yardstick/resources/files/yardstick_key-', self.test_context._name]) mock_genkeys.assert_called_once_with(key_filename) - mock_path_exists.assert_called_once_with(key_filename) + mock_path_exists.assert_any_call(key_filename) @mock.patch.object(heat, 'HeatTemplate', return_value='heat_template') @mock.patch.object(heat.HeatContext, '_add_resources_to_template') @@ -334,7 +334,7 @@ class HeatContextTestCase(unittest.TestCase): 'yardstick/resources/files/yardstick_key-', self.test_context._name_task_id]) mock_genkeys.assert_called_once_with(key_filename) - mock_path_exists.assert_called_with(key_filename) + mock_path_exists.assert_any_call(key_filename) mock_call_gen_keys = mock.call.gen_keys(key_filename) mock_call_add_resources = ( diff --git a/yardstick/tests/unit/benchmark/scenarios/availability/test_scenario_general.py b/yardstick/tests/unit/benchmark/scenarios/availability/test_scenario_general.py index 45840d569..d1172d5a6 100644 --- a/yardstick/tests/unit/benchmark/scenarios/availability/test_scenario_general.py +++ b/yardstick/tests/unit/benchmark/scenarios/availability/test_scenario_general.py @@ -14,7 +14,8 @@ from yardstick.benchmark.scenarios.availability import scenario_general class ScenarioGeneralTestCase(unittest.TestCase): - def setUp(self): + @mock.patch.object(scenario_general, 'Director') + def setUp(self, *args): self.scenario_cfg = { 'type': "general_scenario", 'options': { @@ -36,32 +37,28 @@ class ScenarioGeneralTestCase(unittest.TestCase): } } self.instance = scenario_general.ScenarioGeneral(self.scenario_cfg, None) - - self._mock_director = mock.patch.object(scenario_general, 'Director') - self.mock_director = self._mock_director.start() - self.addCleanup(self._stop_mock) - - def _stop_mock(self): - self._mock_director.stop() + self.instance.setup() + self.instance.director.verify.return_value = True def test_scenario_general_all_successful(self): - self.instance.setup() - self.instance.run({}) + + ret = {} + self.instance.run(ret) self.instance.teardown() + self.assertEqual(ret['sla_pass'], 1) def test_scenario_general_exception(self): - mock_obj = mock.Mock() - mock_obj.createActionPlayer.side_effect = KeyError('Wrong') - self.instance.director = mock_obj + self.instance.director.createActionPlayer.side_effect = KeyError('Wrong') self.instance.director.data = {} - self.instance.run({}) + ret = {} + self.instance.run(ret) self.instance.teardown() + self.assertEqual(ret['sla_pass'], 1) def test_scenario_general_case_fail(self): - mock_obj = mock.Mock() - mock_obj.verify.return_value = False - self.instance.director = mock_obj + self.instance.director.verify.return_value = False self.instance.director.data = {} - self.instance.run({}) - self.instance.pass_flag = True + ret = {} + self.assertRaises(AssertionError, self.instance.run, ret) self.instance.teardown() + self.assertEqual(ret['sla_pass'], 0) diff --git a/yardstick/tests/unit/benchmark/scenarios/availability/test_serviceha.py b/yardstick/tests/unit/benchmark/scenarios/availability/test_serviceha.py index 6bb3ec63b..dd656fbd5 100644 --- a/yardstick/tests/unit/benchmark/scenarios/availability/test_serviceha.py +++ b/yardstick/tests/unit/benchmark/scenarios/availability/test_serviceha.py @@ -60,15 +60,16 @@ class ServicehaTestCase(unittest.TestCase): p.setup() self.assertTrue(p.setup_done) - # def test__serviceha_run_sla_error(self, mock_attacker, mock_monitor): - # p = serviceha.ServiceHA(self.args, self.ctx) + @mock.patch.object(serviceha, 'baseattacker') + @mock.patch.object(serviceha, 'basemonitor') + def test__serviceha_run_sla_error(self, mock_monitor, *args): + p = serviceha.ServiceHA(self.args, self.ctx) - # p.setup() - # self.assertEqual(p.setup_done, True) + p.setup() + self.assertEqual(p.setup_done, True) - # result = {} - # result["outage_time"] = 10 - # mock_monitor.Monitor().get_result.return_value = result + mock_monitor.MonitorMgr().verify_SLA.return_value = False - # ret = {} - # self.assertRaises(AssertionError, p.run, ret) + ret = {} + self.assertRaises(AssertionError, p.run, ret) + self.assertEqual(ret['sla_pass'], 0) diff --git a/yardstick/tests/unit/benchmark/scenarios/lib/test_attach_volume.py b/yardstick/tests/unit/benchmark/scenarios/lib/test_attach_volume.py index 2964ecc14..bb7fa4536 100644 --- a/yardstick/tests/unit/benchmark/scenarios/lib/test_attach_volume.py +++ b/yardstick/tests/unit/benchmark/scenarios/lib/test_attach_volume.py @@ -6,21 +6,51 @@ # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 ############################################################################## +from oslo_utils import uuidutils import unittest import mock -from yardstick.benchmark.scenarios.lib.attach_volume import AttachVolume +from yardstick.common import openstack_utils +from yardstick.common import exceptions +from yardstick.benchmark.scenarios.lib import attach_volume class AttachVolumeTestCase(unittest.TestCase): - @mock.patch('yardstick.common.openstack_utils.attach_server_volume') - def test_attach_volume(self, mock_attach_server_volume): - options = { - 'volume_id': '123-456-000', - 'server_id': '000-123-456' - } - args = {"options": options} - obj = AttachVolume(args, {}) - obj.run({}) - mock_attach_server_volume.assert_called_once() + def setUp(self): + + self._mock_attach_volume_to_server = mock.patch.object( + openstack_utils, 'attach_volume_to_server') + self.mock_attach_volume_to_server = ( + self._mock_attach_volume_to_server.start()) + self._mock_get_shade_client = mock.patch.object( + openstack_utils, 'get_shade_client') + self.mock_get_shade_client = self._mock_get_shade_client.start() + self._mock_log = mock.patch.object(attach_volume, 'LOG') + self.mock_log = self._mock_log.start() + _uuid = uuidutils.generate_uuid() + self.args = {'options': {'server_name_or_id': _uuid, + 'volume_name_or_id': _uuid}} + self.result = {} + self.addCleanup(self._stop_mock) + self.attachvol_obj = attach_volume.AttachVolume(self.args, mock.ANY) + + def _stop_mock(self): + self._mock_attach_volume_to_server.stop() + self._mock_get_shade_client.stop() + self._mock_log.stop() + + def test_run(self): + self.mock_attach_volume_to_server.return_value = True + self.assertIsNone(self.attachvol_obj.run(self.result)) + self.assertEqual({'attach_volume': 1}, self.result) + self.mock_log.info.asset_called_once_with( + 'Attach volume to server successful!') + + def test_run_fail(self): + self.mock_attach_volume_to_server.return_value = False + with self.assertRaises(exceptions.ScenarioAttachVolumeError): + self.attachvol_obj.run(self.result) + self.assertEqual({'attach_volume': 0}, self.result) + self.mock_log.error.assert_called_once_with( + 'Attach volume to server failed!') diff --git a/yardstick/tests/unit/benchmark/scenarios/lib/test_create_floating_ip.py b/yardstick/tests/unit/benchmark/scenarios/lib/test_create_floating_ip.py index a7286f5da..894cc1c2a 100644 --- a/yardstick/tests/unit/benchmark/scenarios/lib/test_create_floating_ip.py +++ b/yardstick/tests/unit/benchmark/scenarios/lib/test_create_floating_ip.py @@ -11,48 +11,47 @@ import unittest import mock from yardstick.benchmark.scenarios.lib import create_floating_ip -import yardstick.common.openstack_utils as op_utils +from yardstick.common import openstack_utils +from yardstick.common import exceptions class CreateFloatingIpTestCase(unittest.TestCase): def setUp(self): - self._mock_get_network_id = mock.patch.object( - op_utils, 'get_network_id') - self.mock_get_network_id = self._mock_get_network_id.start() self._mock_create_floating_ip = mock.patch.object( - op_utils, 'create_floating_ip') + openstack_utils, 'create_floating_ip') self.mock_create_floating_ip = self._mock_create_floating_ip.start() - self._mock_get_neutron_client = mock.patch.object( - op_utils, 'get_neutron_client') - self.mock_get_neutron_client = self._mock_get_neutron_client.start() self._mock_get_shade_client = mock.patch.object( - op_utils, 'get_shade_client') + openstack_utils, 'get_shade_client') self.mock_get_shade_client = self._mock_get_shade_client.start() self._mock_log = mock.patch.object(create_floating_ip, 'LOG') self.mock_log = self._mock_log.start() + self.args = {'options': {'network_name_or_id': 'yardstick_net'}} + self.result = {} - self._fip_obj = create_floating_ip.CreateFloatingIp(mock.ANY, mock.ANY) - self._fip_obj.scenario_cfg = {'output': 'key1\nkey2'} + self.fip_obj = create_floating_ip.CreateFloatingIp(self.args, mock.ANY) + self.fip_obj.scenario_cfg = {'output': 'key1\nkey2'} self.addCleanup(self._stop_mock) def _stop_mock(self): - self._mock_get_network_id.stop() self._mock_create_floating_ip.stop() - self._mock_get_neutron_client.stop() self._mock_get_shade_client.stop() self._mock_log.stop() def test_run(self): self.mock_create_floating_ip.return_value = {'fip_id': 'value1', 'fip_addr': 'value2'} - output = self._fip_obj.run(mock.ANY) - self.assertDictEqual({'key1': 'value1', 'key2': 'value2'}, output) + output = self.fip_obj.run(self.result) + self.assertEqual({'floating_ip_create': 1}, self.result) + self.assertEqual({'key1': 'value1', 'key2': 'value2'}, output) + self.mock_log.info.asset_called_once_with( + 'Creating floating ip successful!') def test_run_no_fip(self): self.mock_create_floating_ip.return_value = None - output = self._fip_obj.run(mock.ANY) - self.assertIsNone(output) + with self.assertRaises(exceptions.ScenarioCreateFloatingIPError): + self.fip_obj.run(self.result) + self.assertEqual({'floating_ip_create': 0}, self.result) self.mock_log.error.assert_called_once_with( 'Creating floating ip failed!') diff --git a/yardstick/tests/unit/benchmark/scenarios/lib/test_create_keypair.py b/yardstick/tests/unit/benchmark/scenarios/lib/test_create_keypair.py index 1c3d6cebc..a7b683f47 100644 --- a/yardstick/tests/unit/benchmark/scenarios/lib/test_create_keypair.py +++ b/yardstick/tests/unit/benchmark/scenarios/lib/test_create_keypair.py @@ -6,22 +6,52 @@ # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 ############################################################################## - -import mock +from oslo_utils import uuidutils import unittest +import mock +from yardstick.common import openstack_utils +from yardstick.common import exceptions from yardstick.benchmark.scenarios.lib import create_keypair class CreateKeypairTestCase(unittest.TestCase): - @mock.patch.object(create_keypair, 'paramiko') - @mock.patch.object(create_keypair, 'op_utils') - def test_create_keypair(self, mock_op_utils, *args): - options = { - 'key_name': 'yardstick_key', - 'key_path': '/tmp/yardstick_key' - } - args = {"options": options} - obj = create_keypair.CreateKeypair(args, {}) - obj.run({}) - mock_op_utils.create_keypair.assert_called_once() + + def setUp(self): + + self._mock_create_keypair = mock.patch.object( + openstack_utils, 'create_keypair') + self.mock_create_keypair = ( + self._mock_create_keypair.start()) + self._mock_get_shade_client = mock.patch.object( + openstack_utils, 'get_shade_client') + self.mock_get_shade_client = self._mock_get_shade_client.start() + self._mock_log = mock.patch.object(create_keypair, 'LOG') + self.mock_log = self._mock_log.start() + self.args = {'options': {'key_name': 'yardstick_key'}} + self.result = {} + + self.ckeypair_obj = create_keypair.CreateKeypair(self.args, mock.ANY) + self.addCleanup(self._stop_mock) + + def _stop_mock(self): + self._mock_create_keypair.stop() + self._mock_get_shade_client.stop() + self._mock_log.stop() + + def test_run(self): + _uuid = uuidutils.generate_uuid() + self.ckeypair_obj.scenario_cfg = {'output': 'id'} + self.mock_create_keypair.return_value = { + 'name': 'key-name', 'type': 'ssh', 'id': _uuid} + output = self.ckeypair_obj.run(self.result) + self.assertDictEqual({'keypair_create': 1}, self.result) + self.assertDictEqual({'id': _uuid}, output) + self.mock_log.info.asset_called_once_with('Create keypair successful!') + + def test_run_fail(self): + self.mock_create_keypair.return_value = None + with self.assertRaises(exceptions.ScenarioCreateKeypairError): + self.ckeypair_obj.run(self.result) + self.assertDictEqual({'keypair_create': 0}, self.result) + self.mock_log.error.assert_called_once_with('Create keypair failed!') diff --git a/yardstick/tests/unit/benchmark/scenarios/lib/test_create_sec_group.py b/yardstick/tests/unit/benchmark/scenarios/lib/test_create_sec_group.py index 21158ab17..0477a49d4 100644 --- a/yardstick/tests/unit/benchmark/scenarios/lib/test_create_sec_group.py +++ b/yardstick/tests/unit/benchmark/scenarios/lib/test_create_sec_group.py @@ -6,25 +6,54 @@ # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 ############################################################################## + +from oslo_utils import uuidutils import unittest import mock -from yardstick.benchmark.scenarios.lib.create_sec_group import CreateSecgroup - - -class CreateSecGroupTestCase(unittest.TestCase): - - @mock.patch('yardstick.common.openstack_utils.get_neutron_client') - @mock.patch('yardstick.common.openstack_utils.create_security_group_full') - def test_create_sec_group(self, mock_get_neutron_client, mock_create_security_group_full): - options = { - 'openstack_paras': { - 'sg_name': 'yardstick_sec_group', - 'description': 'security group for yardstick manual VM' - } - } - args = {"options": options} - obj = CreateSecgroup(args, {}) - obj.run({}) - mock_get_neutron_client.assert_called_once() - mock_create_security_group_full.assert_called_once() +from yardstick.common import openstack_utils +from yardstick.common import exceptions +from yardstick.benchmark.scenarios.lib import create_sec_group + + +class CreateSecurityGroupTestCase(unittest.TestCase): + + def setUp(self): + + self._mock_create_security_group_full = mock.patch.object( + openstack_utils, 'create_security_group_full') + self.mock_create_security_group_full = ( + self._mock_create_security_group_full.start()) + self._mock_get_shade_client = mock.patch.object( + openstack_utils, 'get_shade_client') + self.mock_get_shade_client = self._mock_get_shade_client.start() + self._mock_log = mock.patch.object(create_sec_group, 'LOG') + self.mock_log = self._mock_log.start() + self.args = {'options': {'sg_name': 'yardstick_sg'}} + self.result = {} + + self.csecgp_obj = create_sec_group.CreateSecgroup(self.args, mock.ANY) + self.addCleanup(self._stop_mock) + + def _stop_mock(self): + self._mock_create_security_group_full.stop() + self._mock_get_shade_client.stop() + self._mock_log.stop() + + def test_run(self): + _uuid = uuidutils.generate_uuid() + self.csecgp_obj.scenario_cfg = {'output': 'id'} + self.mock_create_security_group_full.return_value = _uuid + output = self.csecgp_obj.run(self.result) + self.assertEqual({'sg_create': 1}, self.result) + self.assertEqual({'id': _uuid}, output) + self.mock_log.info.asset_called_once_with( + 'Create security group successful!') + + def test_run_fail(self): + self.mock_create_security_group_full.return_value = None + with self.assertRaises(exceptions.ScenarioCreateSecurityGroupError): + self.csecgp_obj.run(self.result) + self.assertEqual({'sg_create': 0}, self.result) + self.mock_log.error.assert_called_once_with( + 'Create security group failed!') diff --git a/yardstick/tests/unit/benchmark/scenarios/lib/test_create_server.py b/yardstick/tests/unit/benchmark/scenarios/lib/test_create_server.py index 9d6d8cb1b..b58785112 100644 --- a/yardstick/tests/unit/benchmark/scenarios/lib/test_create_server.py +++ b/yardstick/tests/unit/benchmark/scenarios/lib/test_create_server.py @@ -6,29 +6,54 @@ # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 ############################################################################## +from oslo_utils import uuidutils import unittest import mock -from yardstick.benchmark.scenarios.lib.create_server import CreateServer +from yardstick.common import openstack_utils +from yardstick.common import exceptions +from yardstick.benchmark.scenarios.lib import create_server class CreateServerTestCase(unittest.TestCase): - @mock.patch('yardstick.common.openstack_utils.create_instance_and_wait_for_active') - @mock.patch('yardstick.common.openstack_utils.get_nova_client') - @mock.patch('yardstick.common.openstack_utils.get_glance_client') - @mock.patch('yardstick.common.openstack_utils.get_neutron_client') - def test_create_server(self, mock_get_nova_client, mock_get_neutron_client, - mock_get_glance_client, mock_create_instance_and_wait_for_active): - scenario_cfg = { - 'options': { - 'openstack_paras': 'example' - }, - 'output': 'server' - } - obj = CreateServer(scenario_cfg, {}) - obj.run({}) - mock_get_nova_client.assert_called_once() - mock_get_glance_client.assert_called_once() - mock_get_neutron_client.assert_called_once() - mock_create_instance_and_wait_for_active.assert_called_once() + def setUp(self): + + self._mock_create_instance_and_wait_for_active = mock.patch.object( + openstack_utils, 'create_instance_and_wait_for_active') + self.mock_create_instance_and_wait_for_active = ( + self._mock_create_instance_and_wait_for_active.start()) + self._mock_get_shade_client = mock.patch.object( + openstack_utils, 'get_shade_client') + self.mock_get_shade_client = self._mock_get_shade_client.start() + self._mock_log = mock.patch.object(create_server, 'LOG') + self.mock_log = self._mock_log.start() + self.args = { + 'options': {'name': 'server-name', 'image': 'image-name', + 'flavor': 'flavor-name'}} + self.result = {} + + self.addCleanup(self._stop_mock) + self.cserver_obj = create_server.CreateServer(self.args, mock.ANY) + + def _stop_mock(self): + self._mock_create_instance_and_wait_for_active.stop() + self._mock_get_shade_client.stop() + self._mock_log.stop() + + def test_run(self): + _uuid = uuidutils.generate_uuid() + self.cserver_obj.scenario_cfg = {'output': 'id'} + self.mock_create_instance_and_wait_for_active.return_value = ( + {'name': 'server-name', 'flavor': 'flavor-name', 'id': _uuid}) + output = self.cserver_obj.run(self.result) + self.assertEqual({'instance_create': 1}, self.result) + self.assertEqual({'id': _uuid}, output) + self.mock_log.info.asset_called_once_with('Create server successful!') + + def test_run_fail(self): + self.mock_create_instance_and_wait_for_active.return_value = None + with self.assertRaises(exceptions.ScenarioCreateServerError): + self.cserver_obj.run(self.result) + self.assertEqual({'instance_create': 0}, self.result) + self.mock_log.error.assert_called_once_with('Create server failed!') diff --git a/yardstick/tests/unit/benchmark/scenarios/lib/test_delete_floating_ip.py b/yardstick/tests/unit/benchmark/scenarios/lib/test_delete_floating_ip.py index 3185ec59f..45a39eba2 100644 --- a/yardstick/tests/unit/benchmark/scenarios/lib/test_delete_floating_ip.py +++ b/yardstick/tests/unit/benchmark/scenarios/lib/test_delete_floating_ip.py @@ -6,22 +6,50 @@ # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 ############################################################################## +from oslo_utils import uuidutils import unittest import mock -from yardstick.benchmark.scenarios.lib.delete_floating_ip import DeleteFloatingIp +from yardstick.common import openstack_utils +from yardstick.common import exceptions +from yardstick.benchmark.scenarios.lib import delete_floating_ip class DeleteFloatingIpTestCase(unittest.TestCase): - @mock.patch('yardstick.common.openstack_utils.get_nova_client') - @mock.patch('yardstick.common.openstack_utils.delete_floating_ip') - def test_delete_floating_ip(self, mock_get_nova_client, mock_delete_floating_ip): - options = { - 'floating_ip_id': '123-123-123' - } - args = {"options": options} - obj = DeleteFloatingIp(args, {}) - obj.run({}) - mock_get_nova_client.assert_called_once() - mock_delete_floating_ip.assert_called_once() + def setUp(self): + self._mock_delete_floating_ip = mock.patch.object( + openstack_utils, 'delete_floating_ip') + self.mock_delete_floating_ip = self._mock_delete_floating_ip.start() + self._mock_get_shade_client = mock.patch.object( + openstack_utils, 'get_shade_client') + self.mock_get_shade_client = self._mock_get_shade_client.start() + self._mock_log = mock.patch.object(delete_floating_ip, 'LOG') + self.mock_log = self._mock_log.start() + self.args = {'options': {'floating_ip_id': uuidutils.generate_uuid()}} + self.result = {} + + self.del_obj = delete_floating_ip.DeleteFloatingIp( + self.args, mock.ANY) + + self.addCleanup(self._stop_mock) + + def _stop_mock(self): + self._mock_delete_floating_ip.stop() + self._mock_get_shade_client.stop() + self._mock_log.stop() + + def test_run(self): + self.mock_delete_floating_ip.return_value = True + self.assertIsNone(self.del_obj.run(self.result)) + self.assertEqual({"delete_floating_ip": 1}, self.result) + self.mock_log.info.assert_called_once_with( + "Delete floating ip successful!") + + def test_run_fail(self): + self.mock_delete_floating_ip.return_value = False + with self.assertRaises(exceptions.ScenarioDeleteFloatingIPError): + self.del_obj.run(self.result) + self.assertEqual({"delete_floating_ip": 0}, self.result) + self.mock_log.error.assert_called_once_with( + "Delete floating ip failed!") diff --git a/yardstick/tests/unit/benchmark/scenarios/lib/test_delete_keypair.py b/yardstick/tests/unit/benchmark/scenarios/lib/test_delete_keypair.py index 6e790ba90..c7940251e 100644 --- a/yardstick/tests/unit/benchmark/scenarios/lib/test_delete_keypair.py +++ b/yardstick/tests/unit/benchmark/scenarios/lib/test_delete_keypair.py @@ -9,19 +9,43 @@ import unittest import mock -from yardstick.benchmark.scenarios.lib.delete_keypair import DeleteKeypair +from yardstick.common import openstack_utils +from yardstick.common import exceptions +from yardstick.benchmark.scenarios.lib import delete_keypair class DeleteKeypairTestCase(unittest.TestCase): - @mock.patch('yardstick.common.openstack_utils.get_nova_client') - @mock.patch('yardstick.common.openstack_utils.delete_keypair') - def test_detach_volume(self, mock_get_nova_client, mock_delete_keypair): - options = { - 'key_name': 'yardstick_key' - } - args = {"options": options} - obj = DeleteKeypair(args, {}) - obj.run({}) - mock_get_nova_client.assert_called_once() - mock_delete_keypair.assert_called_once() + def setUp(self): + self._mock_delete_keypair = mock.patch.object( + openstack_utils, 'delete_keypair') + self.mock_delete_keypair = self._mock_delete_keypair.start() + self._mock_get_shade_client = mock.patch.object( + openstack_utils, 'get_shade_client') + self.mock_get_shade_client = self._mock_get_shade_client.start() + self._mock_log = mock.patch.object(delete_keypair, 'LOG') + self.mock_log = self._mock_log.start() + self.args = {'options': {'key_name': 'yardstick_key'}} + self.result = {} + self.delkey_obj = delete_keypair.DeleteKeypair(self.args, mock.ANY) + + self.addCleanup(self._stop_mock) + + def _stop_mock(self): + self._mock_delete_keypair.stop() + self._mock_get_shade_client.stop() + self._mock_log.stop() + + def test_run(self): + self.mock_delete_keypair.return_value = True + self.assertIsNone(self.delkey_obj.run(self.result)) + self.assertEqual({'delete_keypair': 1}, self.result) + self.mock_log.info.assert_called_once_with( + 'Delete keypair successful!') + + def test_run_fail(self): + self.mock_delete_keypair.return_value = False + with self.assertRaises(exceptions.ScenarioDeleteKeypairError): + self.delkey_obj.run(self.result) + self.assertEqual({'delete_keypair': 0}, self.result) + self.mock_log.error.assert_called_once_with("Delete keypair failed!") diff --git a/yardstick/tests/unit/benchmark/scenarios/lib/test_delete_network.py b/yardstick/tests/unit/benchmark/scenarios/lib/test_delete_network.py index aef99ee94..b6dbf4791 100644 --- a/yardstick/tests/unit/benchmark/scenarios/lib/test_delete_network.py +++ b/yardstick/tests/unit/benchmark/scenarios/lib/test_delete_network.py @@ -11,7 +11,8 @@ from oslo_utils import uuidutils import unittest import mock -import yardstick.common.openstack_utils as op_utils +from yardstick.common import openstack_utils +from yardstick.common import exceptions from yardstick.benchmark.scenarios.lib import delete_network @@ -19,16 +20,17 @@ class DeleteNetworkTestCase(unittest.TestCase): def setUp(self): self._mock_delete_neutron_net = mock.patch.object( - op_utils, 'delete_neutron_net') + openstack_utils, "delete_neutron_net") self.mock_delete_neutron_net = self._mock_delete_neutron_net.start() self._mock_get_shade_client = mock.patch.object( - op_utils, 'get_shade_client') + openstack_utils, "get_shade_client") self.mock_get_shade_client = self._mock_get_shade_client.start() - self._mock_log = mock.patch.object(delete_network, 'LOG') + self._mock_log = mock.patch.object(delete_network, "LOG") self.mock_log = self._mock_log.start() - _uuid = uuidutils.generate_uuid() - self.args = {'options': {'network_id': _uuid}} - self._del_obj = delete_network.DeleteNetwork(self.args, mock.ANY) + self.args = {"options": {"network_name_or_id": ( + uuidutils.generate_uuid())}} + self.result = {} + self.del_obj = delete_network.DeleteNetwork(self.args, mock.ANY) self.addCleanup(self._stop_mock) @@ -39,11 +41,14 @@ class DeleteNetworkTestCase(unittest.TestCase): def test_run(self): self.mock_delete_neutron_net.return_value = True - self.assertTrue(self._del_obj.run({})) + self.assertIsNone(self.del_obj.run(self.result)) + self.assertEqual({"delete_network": 1}, self.result) self.mock_log.info.assert_called_once_with( "Delete network successful!") def test_run_fail(self): self.mock_delete_neutron_net.return_value = False - self.assertFalse(self._del_obj.run({})) + with self.assertRaises(exceptions.ScenarioDeleteNetworkError): + self.del_obj.run(self.result) + self.assertEqual({"delete_network": 0}, self.result) self.mock_log.error.assert_called_once_with("Delete network failed!") diff --git a/yardstick/tests/unit/benchmark/scenarios/lib/test_delete_router_interface.py b/yardstick/tests/unit/benchmark/scenarios/lib/test_delete_router_interface.py index 9e9c5a5b6..823cb951a 100644 --- a/yardstick/tests/unit/benchmark/scenarios/lib/test_delete_router_interface.py +++ b/yardstick/tests/unit/benchmark/scenarios/lib/test_delete_router_interface.py @@ -6,23 +6,51 @@ # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 ############################################################################## + +from oslo_utils import uuidutils import unittest import mock -from yardstick.benchmark.scenarios.lib.delete_router_interface import DeleteRouterInterface +from yardstick.benchmark.scenarios.lib import delete_router_interface +from yardstick.common import openstack_utils +from yardstick.common import exceptions class DeleteRouterInterfaceTestCase(unittest.TestCase): - @mock.patch('yardstick.common.openstack_utils.get_neutron_client') - @mock.patch('yardstick.common.openstack_utils.remove_interface_router') - def test_delete_router_interface(self, mock_get_neutron_client, mock_remove_interface_router): - options = { - 'router_id': '123-123-123', - 'subnet_id': '321-321-321' - } - args = {"options": options} - obj = DeleteRouterInterface(args, {}) - obj.run({}) - mock_get_neutron_client.assert_called_once() - mock_remove_interface_router.assert_called_once() + def setUp(self): + self._mock_remove_router_interface = mock.patch.object( + openstack_utils, 'remove_router_interface') + self.mock_remove_router_interface = ( + self._mock_remove_router_interface.start()) + self._mock_get_shade_client = mock.patch.object( + openstack_utils, 'get_shade_client') + self.mock_get_shade_client = self._mock_get_shade_client.start() + self._mock_log = mock.patch.object(delete_router_interface, 'LOG') + self.mock_log = self._mock_log.start() + self.args = {'options': {'router': uuidutils.generate_uuid()}} + self.result = {} + self.delrout_obj = delete_router_interface.DeleteRouterInterface( + self.args, mock.ANY) + + self.addCleanup(self._stop_mock) + + def _stop_mock(self): + self._mock_remove_router_interface.stop() + self._mock_get_shade_client.stop() + self._mock_log.stop() + + def test_run(self): + self.mock_remove_router_interface.return_value = True + self.assertIsNone(self.delrout_obj.run(self.result)) + self.assertEqual({"delete_router_interface": 1}, self.result) + self.mock_log.info.assert_called_once_with( + "Delete router interface successful!") + + def test_run_fail(self): + self.mock_remove_router_interface.return_value = False + with self.assertRaises(exceptions.ScenarioRemoveRouterIntError): + self.delrout_obj.run(self.result) + self.assertEqual({"delete_router_interface": 0}, self.result) + self.mock_log.error.assert_called_once_with( + "Delete router interface failed!") diff --git a/yardstick/tests/unit/benchmark/scenarios/lib/test_delete_server.py b/yardstick/tests/unit/benchmark/scenarios/lib/test_delete_server.py index eee565de7..55fe53df8 100644 --- a/yardstick/tests/unit/benchmark/scenarios/lib/test_delete_server.py +++ b/yardstick/tests/unit/benchmark/scenarios/lib/test_delete_server.py @@ -6,22 +6,49 @@ # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 ############################################################################## +from oslo_utils import uuidutils import unittest import mock -from yardstick.benchmark.scenarios.lib.delete_server import DeleteServer +from yardstick.common import openstack_utils +from yardstick.common import exceptions +from yardstick.benchmark.scenarios.lib import delete_server class DeleteServerTestCase(unittest.TestCase): - @mock.patch('yardstick.common.openstack_utils.delete_instance') - @mock.patch('yardstick.common.openstack_utils.get_nova_client') - def test_delete_server(self, mock_get_nova_client, mock_delete_instance): - options = { - 'server_id': '1234-4567-0000' - } - args = {"options": options} - obj = DeleteServer(args, {}) - obj.run({}) - mock_get_nova_client.assert_called_once() - mock_delete_instance.assert_called_once() + def setUp(self): + self._mock_delete_instance = mock.patch.object( + openstack_utils, 'delete_instance') + self.mock_delete_instance = ( + self._mock_delete_instance.start()) + self._mock_get_shade_client = mock.patch.object( + openstack_utils, 'get_shade_client') + self.mock_get_shade_client = self._mock_get_shade_client.start() + self._mock_log = mock.patch.object(delete_server, 'LOG') + self.mock_log = self._mock_log.start() + self.args = {'options': {'name_or_id': uuidutils.generate_uuid() + }} + self.result = {} + + self.delserver_obj = delete_server.DeleteServer(self.args, mock.ANY) + + self.addCleanup(self._stop_mock) + + def _stop_mock(self): + self._mock_delete_instance.stop() + self._mock_get_shade_client.stop() + self._mock_log.stop() + + def test_run(self): + self.mock_delete_instance.return_value = True + self.assertIsNone(self.delserver_obj.run(self.result)) + self.assertEqual({'delete_server': 1}, self.result) + self.mock_log.info.assert_called_once_with('Delete server successful!') + + def test_run_fail(self): + self.mock_delete_instance.return_value = False + with self.assertRaises(exceptions.ScenarioDeleteServerError): + self.delserver_obj.run(self.result) + self.assertEqual({'delete_server': 0}, self.result) + self.mock_log.error.assert_called_once_with('Delete server failed!') diff --git a/yardstick/tests/unit/benchmark/scenarios/lib/test_get_flavor.py b/yardstick/tests/unit/benchmark/scenarios/lib/test_get_flavor.py index 15a6f7c8f..1c1364348 100644 --- a/yardstick/tests/unit/benchmark/scenarios/lib/test_get_flavor.py +++ b/yardstick/tests/unit/benchmark/scenarios/lib/test_get_flavor.py @@ -6,20 +6,52 @@ # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 ############################################################################## +from oslo_utils import uuidutils import unittest import mock -from yardstick.benchmark.scenarios.lib.get_flavor import GetFlavor +from yardstick.common import openstack_utils +from yardstick.common import exceptions +from yardstick.benchmark.scenarios.lib import get_flavor class GetFlavorTestCase(unittest.TestCase): - @mock.patch('yardstick.common.openstack_utils.get_flavor_by_name') - def test_get_flavor(self, mock_get_flavor_by_name): - options = { - 'flavor_name': 'yardstick_test_flavor' - } - args = {"options": options} - obj = GetFlavor(args, {}) - obj.run({}) - mock_get_flavor_by_name.assert_called_once() + def setUp(self): + + self._mock_get_flavor = mock.patch.object( + openstack_utils, 'get_flavor') + self.mock_get_flavor = self._mock_get_flavor.start() + self._mock_get_shade_client = mock.patch.object( + openstack_utils, 'get_shade_client') + self.mock_get_shade_client = self._mock_get_shade_client.start() + self._mock_log = mock.patch.object(get_flavor, 'LOG') + self.mock_log = self._mock_log.start() + self.args = {'options': {'name_or_id': 'yardstick_flavor'}} + self.result = {} + + self.getflavor_obj = get_flavor.GetFlavor(self.args, mock.ANY) + self.addCleanup(self._stop_mock) + + def _stop_mock(self): + self._mock_get_flavor.stop() + self._mock_get_shade_client.stop() + self._mock_log.stop() + + def test_run(self): + _uuid = uuidutils.generate_uuid() + self.getflavor_obj.scenario_cfg = {'output': 'flavor'} + self.mock_get_flavor.return_value = ( + {'name': 'flavor-name', 'id': _uuid}) + output = self.getflavor_obj.run(self.result) + self.assertDictEqual({'get_flavor': 1}, self.result) + self.assertDictEqual({'flavor': {'name': 'flavor-name', 'id': _uuid}}, + output) + self.mock_log.info.asset_called_once_with('Get flavor successful!') + + def test_run_fail(self): + self.mock_get_flavor.return_value = None + with self.assertRaises(exceptions.ScenarioGetFlavorError): + self.getflavor_obj.run(self.result) + self.assertDictEqual({'get_flavor': 0}, self.result) + self.mock_log.error.assert_called_once_with('Get flavor failed!') diff --git a/yardstick/tests/unit/benchmark/scenarios/lib/test_get_server.py b/yardstick/tests/unit/benchmark/scenarios/lib/test_get_server.py index 83ec903bc..5b5329cb0 100644 --- a/yardstick/tests/unit/benchmark/scenarios/lib/test_get_server.py +++ b/yardstick/tests/unit/benchmark/scenarios/lib/test_get_server.py @@ -6,37 +6,52 @@ # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 ############################################################################## +from oslo_utils import uuidutils import unittest import mock -from yardstick.benchmark.scenarios.lib.get_server import GetServer +from yardstick.common import openstack_utils +from yardstick.common import exceptions +from yardstick.benchmark.scenarios.lib import get_server class GetServerTestCase(unittest.TestCase): - @mock.patch('yardstick.common.openstack_utils.get_server_by_name') - @mock.patch('yardstick.common.openstack_utils.get_nova_client') - def test_get_server_with_name(self, mock_get_nova_client, mock_get_server_by_name): - scenario_cfg = { - 'options': { - 'server_name': 'yardstick_server' - }, - 'output': 'status server' - } - obj = GetServer(scenario_cfg, {}) - obj.run({}) - mock_get_nova_client.assert_called_once() - mock_get_server_by_name.assert_called_once() - - @mock.patch('yardstick.common.openstack_utils.get_nova_client') - def test_get_server_with_id(self, mock_get_nova_client): - scenario_cfg = { - 'options': { - 'server_id': '1' - }, - 'output': 'status server' - } - mock_get_nova_client().servers.get.return_value = None - obj = GetServer(scenario_cfg, {}) - obj.run({}) - mock_get_nova_client.assert_called() + def setUp(self): + + self._mock_get_server = mock.patch.object( + openstack_utils, 'get_server') + self.mock_get_server = self._mock_get_server.start() + self._mock_get_shade_client = mock.patch.object( + openstack_utils, 'get_shade_client') + self.mock_get_shade_client = self._mock_get_shade_client.start() + self._mock_log = mock.patch.object(get_server, 'LOG') + self.mock_log = self._mock_log.start() + self.args = {'options': {'name_or_id': 'yardstick_key'}} + self.result = {} + + self.getserver_obj = get_server.GetServer(self.args, mock.ANY) + self.addCleanup(self._stop_mock) + + def _stop_mock(self): + self._mock_get_server.stop() + self._mock_get_shade_client.stop() + self._mock_log.stop() + + def test_run(self): + _uuid = uuidutils.generate_uuid() + self.getserver_obj.scenario_cfg = {'output': 'server'} + self.mock_get_server.return_value = ( + {'name': 'server-name', 'id': _uuid}) + output = self.getserver_obj.run(self.result) + self.assertDictEqual({'get_server': 1}, self.result) + self.assertDictEqual({'server': {'name': 'server-name', 'id': _uuid}}, + output) + self.mock_log.info.asset_called_once_with('Get Server successful!') + + def test_run_fail(self): + self.mock_get_server.return_value = None + with self.assertRaises(exceptions.ScenarioGetServerError): + self.getserver_obj.run(self.result) + self.assertDictEqual({'get_server': 0}, self.result) + self.mock_log.error.assert_called_once_with('Get Server failed!') diff --git a/yardstick/tests/unit/benchmark/scenarios/test_base.py b/yardstick/tests/unit/benchmark/scenarios/test_base.py index 985338532..284a71cc8 100644 --- a/yardstick/tests/unit/benchmark/scenarios/test_base.py +++ b/yardstick/tests/unit/benchmark/scenarios/test_base.py @@ -13,10 +13,21 @@ # License for the specific language governing permissions and limitations # under the License. +import time + +import mock + from yardstick.benchmark.scenarios import base from yardstick.tests.unit import base as ut_base +class _TestScenario(base.Scenario): + __scenario_type__ = 'Test Scenario' + + def run(self): + pass + + class ScenarioTestCase(ut_base.BaseUnitTestCase): def test_get_scenario_type(self): @@ -85,6 +96,25 @@ class ScenarioTestCase(ut_base.BaseUnitTestCase): self.assertEqual('No such scenario type %s' % wrong_scenario_name, str(exc.exception)) + def test_scenario_abstract_class(self): + # pylint: disable=abstract-class-instantiated + with self.assertRaises(TypeError): + base.Scenario() + + @mock.patch.object(time, 'sleep') + def test_pre_run_wait_time(self, mock_sleep): + """Ensure default behaviour (backwards compatibility): no wait time""" + test_scenario = _TestScenario() + test_scenario.pre_run_wait_time(mock.ANY) + mock_sleep.assert_not_called() + + @mock.patch.object(time, 'sleep') + def test_post_run_wait_time(self, mock_sleep): + """Ensure default behaviour (backwards compatibility): wait time""" + test_scenario = _TestScenario() + test_scenario.post_run_wait_time(100) + mock_sleep.assert_called_once_with(100) + class IterScenarioClassesTestCase(ut_base.BaseUnitTestCase): diff --git a/yardstick/tests/unit/common/messaging/__init__.py b/yardstick/tests/unit/common/messaging/__init__.py new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/yardstick/tests/unit/common/messaging/__init__.py diff --git a/yardstick/tests/unit/common/messaging/test_consumer.py b/yardstick/tests/unit/common/messaging/test_consumer.py new file mode 100644 index 000000000..612dcaecd --- /dev/null +++ b/yardstick/tests/unit/common/messaging/test_consumer.py @@ -0,0 +1,54 @@ +# Copyright (c) 2018 Intel Corporation +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import mock +from oslo_config import cfg +import oslo_messaging + +from yardstick.common import messaging +from yardstick.common.messaging import consumer +from yardstick.tests.unit import base as ut_base + + +class TestEndPoint(object): + def action_1(self): + pass + + +class _MessagingConsumer(consumer.MessagingConsumer): + pass + + +class MessagingConsumerTestCase(ut_base.BaseUnitTestCase): + + def test__init(self): + with mock.patch.object(oslo_messaging, 'get_rpc_server') as \ + mock_get_rpc_server, \ + mock.patch.object(oslo_messaging, 'get_rpc_transport') as \ + mock_get_rpc_transport, \ + mock.patch.object(oslo_messaging, 'Target') as \ + mock_Target: + mock_get_rpc_transport.return_value = 'test_rpc_transport' + mock_Target.return_value = 'test_Target' + + _MessagingConsumer('test_topic', 'test_pid', [TestEndPoint], + fanout=True) + mock_get_rpc_transport.assert_called_once_with( + cfg.CONF, url=messaging.TRANSPORT_URL) + mock_Target.assert_called_once_with( + topic='test_topic', fanout=True, server=messaging.SERVER) + mock_get_rpc_server.assert_called_once_with( + 'test_rpc_transport', 'test_Target', [TestEndPoint], + executor=messaging.RPC_SERVER_EXECUTOR, + access_policy=oslo_messaging.DefaultRPCAccessPolicy) diff --git a/yardstick/tests/unit/common/messaging/test_payloads.py b/yardstick/tests/unit/common/messaging/test_payloads.py new file mode 100644 index 000000000..00ec220c9 --- /dev/null +++ b/yardstick/tests/unit/common/messaging/test_payloads.py @@ -0,0 +1,46 @@ +# Copyright (c) 2018 Intel Corporation +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from yardstick.common import exceptions +from yardstick.common.messaging import payloads +from yardstick.tests.unit import base as ut_base + + +class _DummyPayload(payloads.Payload): + REQUIRED_FIELDS = {'version', 'key1', 'key2'} + + +class PayloadTestCase(ut_base.BaseUnitTestCase): + + def test__init(self): + payload = _DummyPayload(version=1, key1='value1', key2='value2') + self.assertEqual(1, payload.version) + self.assertEqual('value1', payload.key1) + self.assertEqual('value2', payload.key2) + self.assertEqual(3, len(payload._fields)) + + def test__init_missing_required_fields(self): + with self.assertRaises(exceptions.PayloadMissingAttributes): + _DummyPayload(key1='value1', key2='value2') + + def test_obj_to_dict(self): + payload = _DummyPayload(version=1, key1='value1', key2='value2') + payload_dict = payload.obj_to_dict() + self.assertEqual({'version': 1, 'key1': 'value1', 'key2': 'value2'}, + payload_dict) + + def test_dict_to_obj(self): + _dict = {'version': 2, 'key1': 'value100', 'key2': 'value200'} + payload = _DummyPayload.dict_to_obj(_dict) + self.assertEqual(set(_dict.keys()), payload._fields) diff --git a/yardstick/tests/unit/common/messaging/test_producer.py b/yardstick/tests/unit/common/messaging/test_producer.py new file mode 100644 index 000000000..0289689dc --- /dev/null +++ b/yardstick/tests/unit/common/messaging/test_producer.py @@ -0,0 +1,46 @@ +# Copyright (c) 2018 Intel Corporation +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import mock +from oslo_config import cfg +import oslo_messaging + +from yardstick.common import messaging +from yardstick.common.messaging import producer +from yardstick.tests.unit import base as ut_base + + +class _MessagingProducer(producer.MessagingProducer): + pass + + +class MessagingProducerTestCase(ut_base.BaseUnitTestCase): + + def test__init(self): + with mock.patch.object(oslo_messaging, 'RPCClient') as \ + mock_RPCClient, \ + mock.patch.object(oslo_messaging, 'get_rpc_transport') as \ + mock_get_rpc_transport, \ + mock.patch.object(oslo_messaging, 'Target') as \ + mock_Target: + mock_get_rpc_transport.return_value = 'test_rpc_transport' + mock_Target.return_value = 'test_Target' + + _MessagingProducer('test_topic', 'test_pid', fanout=True) + mock_get_rpc_transport.assert_called_once_with( + cfg.CONF, url=messaging.TRANSPORT_URL) + mock_Target.assert_called_once_with( + topic='test_topic', fanout=True, server=messaging.SERVER) + mock_RPCClient.assert_called_once_with('test_rpc_transport', + 'test_Target') diff --git a/yardstick/tests/unit/common/test_openstack_utils.py b/yardstick/tests/unit/common/test_openstack_utils.py index e39a13f1b..67ca826a5 100644 --- a/yardstick/tests/unit/common/test_openstack_utils.py +++ b/yardstick/tests/unit/common/test_openstack_utils.py @@ -10,8 +10,10 @@ from oslo_utils import uuidutils import unittest import mock - +import shade from shade import exc + +from yardstick.common import constants from yardstick.common import openstack_utils @@ -35,44 +37,44 @@ class GetHeatApiVersionTestCase(unittest.TestCase): self.assertEqual(api_version, expected_result) -class GetNetworkIdTestCase(unittest.TestCase): - - def test_get_network_id(self): - _uuid = uuidutils.generate_uuid() - mock_shade_client = mock.Mock() - mock_shade_client.list_networks = mock.Mock() - mock_shade_client.list_networks.return_value = [{'id': _uuid}] +class GetShadeClientTestCase(unittest.TestCase): - output = openstack_utils.get_network_id(mock_shade_client, - 'network_name') - self.assertEqual(_uuid, output) + @mock.patch.object(shade, 'openstack_cloud', return_value='os_client') + def test_get_shade_client(self, mock_openstack_cloud): + os_cloud_config = {'param1': True, 'param2': 'value2'} + self.assertEqual('os_client', + openstack_utils.get_shade_client(**os_cloud_config)) + os_cloud_config.update(constants.OS_CLOUD_DEFAULT_CONFIG) + mock_openstack_cloud.assert_called_once_with(**os_cloud_config) - def test_get_network_id_no_network(self): - mock_shade_client = mock.Mock() - mock_shade_client.list_networks = mock.Mock() - mock_shade_client.list_networks.return_value = None + mock_openstack_cloud.reset_mock() + os_cloud_config = {'verify': True, 'param2': 'value2'} + self.assertEqual('os_client', + openstack_utils.get_shade_client(**os_cloud_config)) + mock_openstack_cloud.assert_called_once_with(**os_cloud_config) - output = openstack_utils.get_network_id(mock_shade_client, - 'network_name') - self.assertIsNone(output) + @mock.patch.object(shade, 'openstack_cloud', return_value='os_client') + def test_get_shade_client_no_parameters(self, mock_openstack_cloud): + self.assertEqual('os_client', openstack_utils.get_shade_client()) + mock_openstack_cloud.assert_called_once_with( + **constants.OS_CLOUD_DEFAULT_CONFIG) class DeleteNeutronNetTestCase(unittest.TestCase): def setUp(self): self.mock_shade_client = mock.Mock() - self.mock_shade_client.delete_network = mock.Mock() def test_delete_neutron_net(self): self.mock_shade_client.delete_network.return_value = True output = openstack_utils.delete_neutron_net(self.mock_shade_client, - 'network_id') + 'network_name_or_id') self.assertTrue(output) def test_delete_neutron_net_fail(self): self.mock_shade_client.delete_network.return_value = False output = openstack_utils.delete_neutron_net(self.mock_shade_client, - 'network_id') + 'network_name_or_id') self.assertFalse(output) @mock.patch.object(openstack_utils, 'log') @@ -80,7 +82,7 @@ class DeleteNeutronNetTestCase(unittest.TestCase): self.mock_shade_client.delete_network.side_effect = ( exc.OpenStackCloudException('error message')) output = openstack_utils.delete_neutron_net(self.mock_shade_client, - 'network_id') + 'network_name_or_id') self.assertFalse(output) mock_logger.error.assert_called_once() @@ -185,3 +187,352 @@ class CreateNeutronRouterTestCase(unittest.TestCase): self.mock_shade_client) mock_logger.error.assert_called_once() self.assertIsNone(output) + + +class RemoveRouterInterfaceTestCase(unittest.TestCase): + + def setUp(self): + self.mock_shade_client = mock.Mock() + self.router = 'router' + self.mock_shade_client.remove_router_interface = mock.Mock() + + def test_remove_router_interface(self): + self.mock_shade_client.remove_router_interface.return_value = True + output = openstack_utils.remove_router_interface( + self.mock_shade_client, self.router) + self.assertTrue(output) + + @mock.patch.object(openstack_utils, 'log') + def test_remove_router_interface_exception(self, mock_logger): + self.mock_shade_client.remove_router_interface.side_effect = ( + exc.OpenStackCloudException('error message')) + output = openstack_utils.remove_router_interface( + self.mock_shade_client, self.router) + mock_logger.error.assert_called_once() + self.assertFalse(output) + + +class CreateFloatingIpTestCase(unittest.TestCase): + + def setUp(self): + self.mock_shade_client = mock.Mock() + self.network_name_or_id = 'name' + self.mock_shade_client.create_floating_ip = mock.Mock() + + def test_create_floating_ip(self): + self.mock_shade_client.create_floating_ip.return_value = \ + {'floating_ip_address': 'value1', 'id': 'value2'} + output = openstack_utils.create_floating_ip(self.mock_shade_client, + self.network_name_or_id) + self.assertEqual({'fip_addr': 'value1', 'fip_id': 'value2'}, output) + + @mock.patch.object(openstack_utils, 'log') + def test_create_floating_ip_exception(self, mock_logger): + self.mock_shade_client.create_floating_ip.side_effect = ( + exc.OpenStackCloudException('error message')) + output = openstack_utils.create_floating_ip( + self.mock_shade_client, self.network_name_or_id) + mock_logger.error.assert_called_once() + self.assertIsNone(output) + + +class DeleteFloatingIpTestCase(unittest.TestCase): + + def setUp(self): + self.mock_shade_client = mock.Mock() + self.floating_ip_id = 'floating_ip_id' + self.mock_shade_client.delete_floating_ip = mock.Mock() + + def test_delete_floating_ip(self): + self.mock_shade_client.delete_floating_ip.return_value = True + output = openstack_utils.delete_floating_ip(self.mock_shade_client, + 'floating_ip_id') + self.assertTrue(output) + + def test_delete_floating_ip_fail(self): + self.mock_shade_client.delete_floating_ip.return_value = False + output = openstack_utils.delete_floating_ip(self.mock_shade_client, + 'floating_ip_id') + self.assertFalse(output) + + @mock.patch.object(openstack_utils, 'log') + def test_delete_floating_ip_exception(self, mock_logger): + self.mock_shade_client.delete_floating_ip.side_effect = ( + exc.OpenStackCloudException('error message')) + output = openstack_utils.delete_floating_ip(self.mock_shade_client, + 'floating_ip_id') + mock_logger.error.assert_called_once() + self.assertFalse(output) + + +class CreateSecurityGroupRuleTestCase(unittest.TestCase): + + def setUp(self): + self.mock_shade_client = mock.Mock() + self.secgroup_name_or_id = 'sg_name_id' + self.mock_shade_client.create_security_group_rule = mock.Mock() + + def test_create_security_group_rule(self): + self.mock_shade_client.create_security_group_rule.return_value = ( + {'security_group_rule'}) + output = openstack_utils.create_security_group_rule( + self.mock_shade_client, self.secgroup_name_or_id) + self.assertTrue(output) + + @mock.patch.object(openstack_utils, 'log') + def test_create_security_group_rule_exception(self, mock_logger): + self.mock_shade_client.create_security_group_rule.side_effect = ( + exc.OpenStackCloudException('error message')) + + output = openstack_utils.create_security_group_rule( + self.mock_shade_client, self.secgroup_name_or_id) + mock_logger.error.assert_called_once() + self.assertFalse(output) + + +class ListImageTestCase(unittest.TestCase): + + def test_list_images(self): + mock_shade_client = mock.MagicMock() + mock_shade_client.list_images.return_value = [] + openstack_utils.list_images(mock_shade_client) + + @mock.patch.object(openstack_utils, 'log') + def test_list_images_exception(self, mock_logger): + mock_shade_client = mock.MagicMock() + mock_shade_client.list_images = mock.MagicMock() + mock_shade_client.list_images.side_effect = ( + exc.OpenStackCloudException('error message')) + images = openstack_utils.list_images(mock_shade_client) + mock_logger.error.assert_called_once() + self.assertFalse(images) + + +class SecurityGroupTestCase(unittest.TestCase): + + def setUp(self): + self.mock_shade_client = mock.Mock() + self.sg_name = 'sg_name' + self.sg_description = 'sg_description' + self._uuid = uuidutils.generate_uuid() + + def test_create_security_group_full_existing_security_group(self): + self.mock_shade_client.get_security_group.return_value = ( + {'name': 'name', 'id': self._uuid}) + output = openstack_utils.create_security_group_full( + self.mock_shade_client, self.sg_name, self.sg_description) + self.mock_shade_client.get_security_group.assert_called_once() + self.assertEqual(self._uuid, output) + + @mock.patch.object(openstack_utils, 'log') + def test_create_security_group_full_non_existing_security_group( + self, mock_logger): + self.mock_shade_client.get_security_group.return_value = None + self.mock_shade_client.create_security_group.side_effect = ( + exc.OpenStackCloudException('error message')) + output = openstack_utils.create_security_group_full( + self.mock_shade_client, self.sg_name, self.sg_description) + mock_logger.error.assert_called_once() + self.assertIsNone(output) + + @mock.patch.object(openstack_utils, 'create_security_group_rule') + @mock.patch.object(openstack_utils, 'log') + def test_create_security_group_full_create_rule_fail( + self, mock_logger, mock_create_security_group_rule): + self.mock_shade_client.get_security_group.return_value = None + self.mock_shade_client.create_security_group.return_value = ( + {'name': 'name', 'id': self._uuid}) + mock_create_security_group_rule.return_value = False + output = openstack_utils.create_security_group_full( + self.mock_shade_client, self.sg_name, self.sg_description) + mock_create_security_group_rule.assert_called() + self.mock_shade_client.delete_security_group(self.sg_name) + mock_logger.error.assert_called_once() + self.assertIsNone(output) + + @mock.patch.object(openstack_utils, 'create_security_group_rule') + def test_create_security_group_full( + self, mock_create_security_group_rule): + self.mock_shade_client.get_security_group.return_value = None + self.mock_shade_client.create_security_group.return_value = ( + {'name': 'name', 'id': self._uuid}) + mock_create_security_group_rule.return_value = True + output = openstack_utils.create_security_group_full( + self.mock_shade_client, self.sg_name, self.sg_description) + mock_create_security_group_rule.assert_called() + self.mock_shade_client.delete_security_group(self.sg_name) + self.assertEqual(self._uuid, output) + +# ********************************************* +# NOVA +# ********************************************* + + +class CreateInstanceTestCase(unittest.TestCase): + + def test_create_instance_and_wait_for_active(self): + self.mock_shade_client = mock.Mock() + name = 'server_name' + image = 'image_name' + flavor = 'flavor_name' + self.mock_shade_client.create_server.return_value = ( + {'name': name, 'image': image, 'flavor': flavor}) + output = openstack_utils.create_instance_and_wait_for_active( + self.mock_shade_client, name, image, flavor) + self.assertEqual( + {'name': name, 'image': image, 'flavor': flavor}, output) + + @mock.patch.object(openstack_utils, 'log') + def test_create_instance_and_wait_for_active_fail(self, mock_logger): + self.mock_shade_client = mock.Mock() + self.mock_shade_client.create_server.side_effect = ( + exc.OpenStackCloudException('error message')) + output = openstack_utils.create_instance_and_wait_for_active( + self.mock_shade_client, 'server_name', 'image_name', 'flavor_name') + mock_logger.error.assert_called_once() + self.assertIsNone(output) + + +class DeleteInstanceTestCase(unittest.TestCase): + + def setUp(self): + self.mock_shade_client = mock.Mock() + + def test_delete_instance(self): + self.mock_shade_client.delete_server.return_value = True + output = openstack_utils.delete_instance(self.mock_shade_client, + 'instance_name_id') + self.assertTrue(output) + + def test_delete_instance_fail(self): + self.mock_shade_client.delete_server.return_value = False + output = openstack_utils.delete_instance(self.mock_shade_client, + 'instance_name_id') + self.assertFalse(output) + + @mock.patch.object(openstack_utils, 'log') + def test_delete_instance_exception(self, mock_logger): + self.mock_shade_client.delete_server.side_effect = ( + exc.OpenStackCloudException('error message')) + output = openstack_utils.delete_instance(self.mock_shade_client, + 'instance_name_id') + mock_logger.error.assert_called_once() + self.assertFalse(output) + + +class CreateKeypairTestCase(unittest.TestCase): + + def setUp(self): + self.mock_shade_client = mock.Mock() + self.name = 'key_name' + + def test_create_keypair(self): + self.mock_shade_client.create_keypair.return_value = ( + {'name': 'key-name', 'type': 'ssh'}) + output = openstack_utils.create_keypair( + self.mock_shade_client, self.name) + self.assertEqual( + {'name': 'key-name', 'type': 'ssh'}, + output) + + @mock.patch.object(openstack_utils, 'log') + def test_create_keypair_fail(self, mock_logger): + self.mock_shade_client.create_keypair.side_effect = ( + exc.OpenStackCloudException('error message')) + output = openstack_utils.create_keypair( + self.mock_shade_client, self.name) + mock_logger.error.assert_called_once() + self.assertIsNone(output) + + +class DeleteKeypairTestCase(unittest.TestCase): + + def setUp(self): + self.mock_shade_client = mock.Mock() + + def test_delete_keypair(self): + self.mock_shade_client.delete_keypair.return_value = True + output = openstack_utils.delete_keypair(self.mock_shade_client, + 'key_name') + self.assertTrue(output) + + def test_delete_keypair_fail(self): + self.mock_shade_client.delete_keypair.return_value = False + output = openstack_utils.delete_keypair(self.mock_shade_client, + 'key_name') + self.assertFalse(output) + + @mock.patch.object(openstack_utils, 'log') + def test_delete_keypair_exception(self, mock_logger): + self.mock_shade_client.delete_keypair.side_effect = ( + exc.OpenStackCloudException('error message')) + output = openstack_utils.delete_keypair(self.mock_shade_client, + 'key_name') + mock_logger.error.assert_called_once() + self.assertFalse(output) + + +class AttachVolumeToServerTestCase(unittest.TestCase): + + def test_attach_volume_to_server(self): + self.mock_shade_client = mock.Mock() + self.mock_shade_client.get_server.return_value = {'server_dict'} + self.mock_shade_client.get_volume.return_value = {'volume_dict'} + self.mock_shade_client.attach_volume.return_value = True + output = openstack_utils.attach_volume_to_server( + self.mock_shade_client, 'server_name_or_id', 'volume_name_or_id') + self.assertTrue(output) + + @mock.patch.object(openstack_utils, 'log') + def test_attach_volume_to_server_fail(self, mock_logger): + self.mock_shade_client = mock.Mock() + self.mock_shade_client.attach_volume.side_effect = ( + exc.OpenStackCloudException('error message')) + output = openstack_utils.attach_volume_to_server( + self.mock_shade_client, 'server_name_or_id', 'volume_name_or_id') + mock_logger.error.assert_called_once() + self.assertFalse(output) + + +class GetServerTestCase(unittest.TestCase): + + def test_get_server(self): + self.mock_shade_client = mock.Mock() + _uuid = uuidutils.generate_uuid() + self.mock_shade_client.get_server.return_value = { + 'name': 'server_name', 'id': _uuid} + output = openstack_utils.get_server(self.mock_shade_client, + 'server_name_or_id') + self.assertEqual({'name': 'server_name', 'id': _uuid}, output) + + @mock.patch.object(openstack_utils, 'log') + def test_get_server_exception(self, mock_logger): + self.mock_shade_client = mock.Mock() + self.mock_shade_client.get_server.side_effect = ( + exc.OpenStackCloudException('error message')) + output = openstack_utils.get_server(self.mock_shade_client, + 'server_name_or_id') + mock_logger.error.assert_called_once() + self.assertIsNone(output) + + +class GetFlavorTestCase(unittest.TestCase): + + def test_get_flavor(self): + self.mock_shade_client = mock.Mock() + _uuid = uuidutils.generate_uuid() + self.mock_shade_client.get_flavor.return_value = { + 'name': 'flavor_name', 'id': _uuid} + output = openstack_utils.get_flavor(self.mock_shade_client, + 'flavor_name_or_id') + self.assertEqual({'name': 'flavor_name', 'id': _uuid}, output) + + @mock.patch.object(openstack_utils, 'log') + def test_get_flavor_exception(self, mock_logger): + self.mock_shade_client = mock.Mock() + self.mock_shade_client.get_flavor.side_effect = ( + exc.OpenStackCloudException('error message')) + output = openstack_utils.get_flavor(self.mock_shade_client, + 'flavor_name_or_id') + mock_logger.error.assert_called_once() + self.assertIsNone(output) diff --git a/yardstick/tests/unit/common/test_utils.py b/yardstick/tests/unit/common/test_utils.py index 9540a39e8..666b29b5f 100644 --- a/yardstick/tests/unit/common/test_utils.py +++ b/yardstick/tests/unit/common/test_utils.py @@ -16,13 +16,15 @@ import mock import os import six from six.moves import configparser +import time import unittest import yardstick from yardstick import ssh import yardstick.error -from yardstick.common import utils from yardstick.common import constants +from yardstick.common import utils +from yardstick.common import exceptions class IterSubclassesTestCase(unittest.TestCase): @@ -1158,3 +1160,43 @@ class ReadMeminfoTestCase(unittest.TestCase): output = utils.read_meminfo(ssh_client) mock_get_client.assert_called_once_with('/proc/meminfo', mock.ANY) self.assertEqual(self.MEMINFO_DICT, output) + + +class TimerTestCase(unittest.TestCase): + + def test__getattr(self): + with utils.Timer() as timer: + time.sleep(1) + self.assertEqual(1, round(timer.total_seconds(), 0)) + self.assertEqual(1, timer.delta.seconds) + + def test__enter_with_timeout(self): + with utils.Timer(timeout=10) as timer: + time.sleep(1) + self.assertEqual(1, round(timer.total_seconds(), 0)) + + def test__enter_with_timeout_exception(self): + with self.assertRaises(exceptions.TimerTimeout): + with utils.Timer(timeout=1): + time.sleep(2) + + +class WaitUntilTrueTestCase(unittest.TestCase): + + def test_no_timeout(self): + self.assertIsNone(utils.wait_until_true(lambda: True, + timeout=1, sleep=1)) + + def test_timeout_generic_exception(self): + with self.assertRaises(exceptions.WaitTimeout): + self.assertIsNone(utils.wait_until_true(lambda: False, + timeout=1, sleep=1)) + + def test_timeout_given_exception(self): + class MyTimeoutException(exceptions.YardstickException): + message = 'My timeout exception' + + with self.assertRaises(MyTimeoutException): + self.assertIsNone( + utils.wait_until_true(lambda: False, timeout=1, sleep=1, + exception=MyTimeoutException)) diff --git a/yardstick/tests/unit/network_services/__init__.py b/yardstick/tests/unit/network_services/__init__.py new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/yardstick/tests/unit/network_services/__init__.py diff --git a/yardstick/tests/unit/network_services/collector/__init__.py b/yardstick/tests/unit/network_services/collector/__init__.py new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/yardstick/tests/unit/network_services/collector/__init__.py diff --git a/yardstick/tests/unit/network_services/collector/test_publisher.py b/yardstick/tests/unit/network_services/collector/test_publisher.py new file mode 100644 index 000000000..145441ddd --- /dev/null +++ b/yardstick/tests/unit/network_services/collector/test_publisher.py @@ -0,0 +1,36 @@ +# Copyright (c) 2016-2017 Intel Corporation +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import unittest + +from yardstick.network_services.collector import publisher + + +class PublisherTestCase(unittest.TestCase): + + def setUp(self): + self.test_publisher = publisher.Publisher() + + def test_successful_init(self): + pass + + def test_unsuccessful_init(self): + pass + + def test_start(self): + self.assertIsNone(self.test_publisher.start()) + + def test_stop(self): + self.assertIsNone(self.test_publisher.stop()) diff --git a/yardstick/tests/unit/network_services/collector/test_subscriber.py b/yardstick/tests/unit/network_services/collector/test_subscriber.py new file mode 100644 index 000000000..a344f5c85 --- /dev/null +++ b/yardstick/tests/unit/network_services/collector/test_subscriber.py @@ -0,0 +1,94 @@ +# Copyright (c) 2016-2017 Intel Corporation +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import unittest +import mock + +from yardstick.network_services.collector import subscriber + + +class MockVnfAprrox(object): + + def __init__(self): + self.result = {} + self.name = "vnf__1" + + def collect_kpi(self): + self.result = { + 'pkt_in_up_stream': 100, + 'pkt_drop_up_stream': 5, + 'pkt_in_down_stream': 50, + 'pkt_drop_down_stream': 40 + } + return self.result + + +class CollectorTestCase(unittest.TestCase): + + NODES = { + 'node1': {}, + 'node2': { + 'ip': '1.2.3.4', + 'collectd': { + 'plugins': {'abc': 12, 'def': 34}, + 'interval': 987, + }, + }, + } + TRAFFIC_PROFILE = { + 'key1': 'value1', + } + + def setUp(self): + vnf = MockVnfAprrox() + self.ssh_patch = mock.patch('yardstick.network_services.nfvi.resource.ssh', autospec=True) + mock_ssh = self.ssh_patch.start() + mock_instance = mock.Mock() + mock_instance.execute.return_value = 0, '', '' + mock_ssh.AutoConnectSSH.from_node.return_value = mock_instance + self.collector = subscriber.Collector([vnf], self.NODES, self.TRAFFIC_PROFILE, 1800) + + def tearDown(self): + self.ssh_patch.stop() + + def test___init__(self, *_): + vnf = MockVnfAprrox() + collector = subscriber.Collector([vnf], {}, {}) + self.assertEqual(len(collector.vnfs), 1) + self.assertEqual(collector.traffic_profile, {}) + + def test___init___with_data(self, *_): + self.assertEqual(len(self.collector.vnfs), 1) + self.assertDictEqual(self.collector.traffic_profile, self.TRAFFIC_PROFILE) + self.assertEqual(len(self.collector.resource_profiles), 1) + + def test___init___negative(self, *_): + pass + + def test_start(self, *_): + with self.assertRaises(Exception): + self.collector.start() + + def test_stop(self, *_): + self.assertIsNone(self.collector.stop()) + + def test_get_kpi(self, *_): + result = self.collector.get_kpi() + + self.assertEqual(result["vnf__1"]["pkt_in_up_stream"], 100) + self.assertEqual(result["vnf__1"]["pkt_drop_up_stream"], 5) + self.assertEqual(result["vnf__1"]["pkt_in_down_stream"], 50) + self.assertEqual(result["vnf__1"]["pkt_drop_down_stream"], 40) + self.assertIn('node2', result) diff --git a/yardstick/tests/unit/network_services/libs/__init__.py b/yardstick/tests/unit/network_services/libs/__init__.py new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/yardstick/tests/unit/network_services/libs/__init__.py diff --git a/yardstick/tests/unit/network_services/libs/ixia_libs/__init__.py b/yardstick/tests/unit/network_services/libs/ixia_libs/__init__.py new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/yardstick/tests/unit/network_services/libs/ixia_libs/__init__.py diff --git a/yardstick/tests/unit/network_services/libs/ixia_libs/test_IxNet.py b/yardstick/tests/unit/network_services/libs/ixia_libs/test_IxNet.py new file mode 100644 index 000000000..7ca2f0f19 --- /dev/null +++ b/yardstick/tests/unit/network_services/libs/ixia_libs/test_IxNet.py @@ -0,0 +1,874 @@ +# Copyright (c) 2016-2017 Intel Corporation +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import mock +import IxNetwork +import unittest + +from yardstick.network_services.libs.ixia_libs.IxNet.IxNet import IxNextgen +from yardstick.network_services.libs.ixia_libs.IxNet.IxNet import IP_VERSION_4 +from yardstick.network_services.libs.ixia_libs.IxNet.IxNet import IP_VERSION_6 + +UPLINK = "uplink" +DOWNLINK = "downlink" + + +class TestIxNextgen(unittest.TestCase): + + def test___init__(self): + ixnet_gen = IxNextgen() + self.assertIsNone(ixnet_gen._bidir) + + @mock.patch.object(IxNetwork, 'IxNet') + def test_connect(self, mock_ixnet): + ixnet_instance = mock.Mock() + mock_ixnet.return_value = ixnet_instance + ixnet_gen = IxNextgen() + with mock.patch.object(ixnet_gen, 'get_config') as mock_config: + mock_config.return_value = {'machine': 'machine_fake', + 'port': 'port_fake', + 'version': 12345} + ixnet_gen._connect(mock.ANY) + + ixnet_instance.connect.assert_called_once_with( + 'machine_fake', '-port', 'port_fake', '-version', '12345') + mock_config.assert_called_once() + + def test_clear_ixia_config(self): + ixnet = mock.MagicMock() + ixnet.execute = mock.Mock() + + ixnet_gen = IxNextgen(ixnet) + + result = ixnet_gen.clear_ixia_config() + self.assertIsNone(result) + self.assertEqual(ixnet.execute.call_count, 1) + + def test_load_ixia_profile(self): + ixnet = mock.MagicMock() + ixnet.execute = mock.Mock() + + ixnet_gen = IxNextgen(ixnet) + + result = ixnet_gen.load_ixia_profile({}) + self.assertIsNone(result) + self.assertEqual(ixnet.execute.call_count, 1) + + def test_load_ixia_config(self): + ixnet = mock.MagicMock() + ixnet.execute = mock.Mock() + + ixnet_gen = IxNextgen(ixnet) + + result = ixnet_gen.ix_load_config({}) + self.assertIsNone(result) + self.assertEqual(ixnet.execute.call_count, 2) + + @mock.patch('yardstick.network_services.libs.ixia_libs.IxNet.IxNet.log') + def test_ix_assign_ports(self, mock_logger): + ixnet = mock.MagicMock() + ixnet.getList.return_value = [0, 1] + ixnet.getAttribute.side_effect = ['up', 'down'] + + config = { + 'chassis': '1.1.1.1', + 'cards': ['1', '2'], + 'ports': ['2', '2'], + } + + ixnet_gen = IxNextgen(ixnet) + ixnet_gen._cfg = config + + result = ixnet_gen.ix_assign_ports() + self.assertIsNone(result) + self.assertEqual(ixnet.execute.call_count, 1) + self.assertEqual(ixnet.commit.call_count, 1) + self.assertEqual(ixnet.getAttribute.call_count, 2) + self.assertEqual(mock_logger.error.call_count, 1) + + def test_ix_update_frame(self): + static_traffic_params = { + UPLINK: { + "id": 1, + "bidir": "False", + "duration": 60, + "iload": "100", + "outer_l2": { + "dstmac": "00:00:00:00:00:03", + "framesPerSecond": True, + "framesize": { + "64B": "100", + "1KB": "0", + }, + "srcmac": "00:00:00:00:00:01" + }, + "outer_l3": { + "dscp": 0, + "dstip4": "152.16.40.20", + "proto": "udp", + "srcip4": "152.16.100.20", + "ttl": 32 + }, + "outer_l3v4": { + "dscp": 0, + "dstip4": "152.16.40.20", + "proto": "udp", + "srcip4": "152.16.100.20", + "ttl": 32 + }, + "outer_l3v6": { + "count": 1024, + "dscp": 0, + "dstip4": "152.16.100.20", + "proto": "udp", + "srcip4": "152.16.40.20", + "ttl": 32 + }, + "outer_l4": { + "dstport": "2001", + "srcport": "1234" + }, + "traffic_type": "continuous" + }, + DOWNLINK: { + "id": 2, + "bidir": "False", + "duration": 60, + "iload": "100", + "outer_l2": { + "dstmac": "00:00:00:00:00:04", + "framesPerSecond": False, + "framesize": {"64B": "100"}, + "srcmac": "00:00:00:00:00:01" + }, + "outer_l3": { + "count": 1024, + "dscp": 0, + "dstip4": "152.16.100.20", + "proto": "udp", + "srcip4": "152.16.40.20", + "ttl": 32 + }, + "outer_l3v4": { + "count": 1024, + "dscp": 0, + "dstip4": "152.16.100.20", + "proto": "udp", + "srcip4": "152.16.40.20", + "ttl": 32 + }, + "outer_l3v6": { + "count": 1024, + "dscp": 0, + "dstip4": "152.16.100.20", + "proto": "udp", + "srcip4": "152.16.40.20", + "ttl": 32 + }, + "outer_l4": { + "dstport": "1234", + "srcport": "2001" + }, + "traffic_type": "continuous" + } + } + + ixnet = mock.MagicMock() + ixnet.remapIds.return_value = ["0"] + ixnet.setMultiAttribute.return_value = [1] + ixnet.commit.return_value = [1] + ixnet.getList.side_effect = [ + [1], + [1], + [1], + [ + "ethernet.header.destinationAddress", + "ethernet.header.sourceAddress", + ], + ] + + ixnet_gen = IxNextgen(ixnet) + + result = ixnet_gen.ix_update_frame(static_traffic_params) + self.assertIsNone(result) + self.assertEqual(ixnet.setMultiAttribute.call_count, 7) + self.assertEqual(ixnet.commit.call_count, 2) + + def test_ix_update_udp(self): + ixnet = mock.MagicMock() + + ixnet_gen = IxNextgen(ixnet) + + result = ixnet_gen.ix_update_udp({}) + self.assertIsNone(result) + + def test_ix_update_tcp(self): + ixnet = mock.MagicMock() + ixnet_gen = IxNextgen(ixnet) + + result = ixnet_gen.ix_update_tcp({}) + self.assertIsNone(result) + + def test_ix_start_traffic(self): + ixnet = mock.MagicMock() + ixnet.getList.return_value = [0] + ixnet.getAttribute.return_value = 'down' + + ixnet_gen = IxNextgen(ixnet) + + result = ixnet_gen.ix_start_traffic() + self.assertIsNone(result) + self.assertEqual(ixnet.getList.call_count, 1) + self.assertEqual(ixnet.execute.call_count, 3) + + def test_ix_stop_traffic(self): + ixnet = mock.MagicMock() + ixnet.getList.return_value = [0] + + ixnet_gen = IxNextgen(ixnet) + + result = ixnet_gen.ix_stop_traffic() + self.assertIsNone(result) + self.assertEqual(ixnet.getList.call_count, 1) + self.assertEqual(ixnet.execute.call_count, 1) + + def test_ix_get_statistics(self): + ixnet = mock.MagicMock() + ixnet.execute.return_value = "" + ixnet.getList.side_effect = [ + [ + '::ixNet::OBJ-/statistics/view:"Traffic Item Statistics"', + '::ixNet::OBJ-/statistics/view:"Port Statistics"', + ], + [ + '::ixNet::OBJ-/statistics/view:"Flow Statistics"', + ], + ] + + ixnet_gen = IxNextgen(ixnet) + + result = ixnet_gen.ix_get_statistics() + self.assertIsNotNone(result) + self.assertEqual(ixnet.getList.call_count, 1) + self.assertEqual(ixnet.execute.call_count, 20) + + def test_find_view_obj_no_where(self): + views = ['here', 'there', 'everywhere'] + result = IxNextgen.find_view_obj('no_where', views) + self.assertEqual(result, '') + + def test_add_ip_header_v4(self): + static_traffic_params = { + "uplink_0": { + "id": 1, + "bidir": "False", + "duration": 60, + "iload": "100", + "outer_l2": { + "dstmac": "00:00:00:00:00:03", + "framesPerSecond": True, + "framesize": {"64B": "100"}, + "srcmac": "00:00:00:00:00:01" + }, + "outer_l3": { + "dscp": 0, + "dstip4": "152.16.40.20", + "proto": "udp", + "srcip4": "152.16.100.20", + "count": 1024, + "ttl": 32 + }, + "outer_l3v4": { + "dscp": 0, + "dstip4": "152.16.40.20", + "proto": "udp", + "srcip4": "152.16.100.20", + "ttl": 32 + }, + "outer_l3v6": { + "count": 1024, + "dscp": 0, + "dstip4": "152.16.100.20", + "proto": "udp", + "srcip4": "152.16.40.20", + "ttl": 32 + }, + "outer_l4": { + "dstport": "2001", + "srcport": "1234" + }, + "traffic_type": "continuous" + }, + "downlink_0": { + "id": 2, + "bidir": "False", + "duration": 60, + "iload": "100", + "outer_l2": { + "dstmac": "00:00:00:00:00:04", + "framesPerSecond": True, + "framesize": {"64B": "100"}, + "srcmac": "00:00:00:00:00:01" + }, + "outer_l3": { + "count": 1024, + "dscp": 0, + "dstip4": "152.16.100.20", + "proto": "udp", + "srcip4": "152.16.40.20", + "ttl": 32 + }, + "outer_l3v4": { + "count": 1024, + "dscp": 0, + "dstip4": "152.16.100.20", + "proto": "udp", + "srcip4": "152.16.40.20", + "ttl": 32 + }, + "outer_l3v6": { + "count": 1024, + "dscp": 0, + "dstip4": "152.16.100.20", + "proto": "udp", + "srcip4": "152.16.40.20", + "ttl": 32 + }, + "outer_l4": { + "dstport": "1234", + "srcport": "2001" + }, + "traffic_type": "continuous" + } + } + + ixnet = mock.MagicMock() + ixnet.remapIds.return_value = ["0"] + ixnet.setMultiAttribute.return_value = [1] + ixnet.commit.return_value = [1] + ixnet.getList.side_effect = [[1], [0], [0], ["srcIp", "dstIp"]] + + ixnet_gen = IxNextgen(ixnet) + + result = ixnet_gen.add_ip_header(static_traffic_params, IP_VERSION_4) + self.assertIsNone(result) + self.assertGreater(ixnet.setMultiAttribute.call_count, 0) + self.assertEqual(ixnet.commit.call_count, 1) + + def test_add_ip_header_v4_nothing_to_do(self): + static_traffic_params = { + "uplink_0": { + "id": 1, + "bidir": "False", + "duration": 60, + "iload": "100", + "outer_l2": { + "dstmac": "00:00:00:00:00:03", + "framesPerSecond": True, + "framesize": {"64B": "100"}, + "srcmac": "00:00:00:00:00:01" + }, + "outer_l3": { + "dscp": 0, + "dstip4": "152.16.40.20", + "proto": "udp", + "srcip4": "152.16.100.20", + "count": 1024, + "ttl": 32 + }, + "outer_l3v4": { + "dscp": 0, + "dstip4": "152.16.40.20", + "proto": "udp", + "srcip4": "152.16.100.20", + "ttl": 32 + }, + "outer_l3v6": { + "count": 1024, + "dscp": 0, + "dstip4": "152.16.100.20", + "proto": "udp", + "srcip4": "152.16.40.20", + "ttl": 32 + }, + "outer_l4": { + "dstport": "2001", + "srcport": "1234" + }, + "traffic_type": "continuous" + }, + "downlink_0": { + "id": 2, + "bidir": "False", + "duration": 60, + "iload": "100", + "outer_l2": { + "dstmac": "00:00:00:00:00:04", + "framesPerSecond": True, + "framesize": {"64B": "100"}, + "srcmac": "00:00:00:00:00:01" + }, + "outer_l3": { + "count": 1024, + "dscp": 0, + "dstip4": "152.16.100.20", + "proto": "udp", + "srcip4": "152.16.40.20", + "ttl": 32 + }, + "outer_l3v4": { + "count": 1024, + "dscp": 0, + "dstip4": "152.16.100.20", + "proto": "udp", + "srcip4": "152.16.40.20", + "ttl": 32 + }, + "outer_l3v6": { + "count": 1024, + "dscp": 0, + "dstip4": "152.16.100.20", + "proto": "udp", + "srcip4": "152.16.40.20", + "ttl": 32 + }, + "outer_l4": { + "dstport": "1234", + "srcport": "2001" + }, + "traffic_type": "continuous" + } + } + + ixnet = mock.MagicMock() + ixnet.remapIds.return_value = ["0"] + ixnet.setMultiAttribute.return_value = [1] + ixnet.commit.return_value = [1] + ixnet.getList.side_effect = [[1], [0, 1], [0], ["srcIp", "dstIp"]] + + ixnet_gen = IxNextgen(ixnet) + + result = ixnet_gen.add_ip_header(static_traffic_params, IP_VERSION_4) + self.assertIsNone(result) + self.assertGreater(ixnet.setMultiAttribute.call_count, 0) + self.assertEqual(ixnet.commit.call_count, 1) + + def test_add_ip_header_v6(self): + static_traffic_profile = { + "uplink_0": { + "id": 1, + "bidir": "False", + "duration": 60, + "iload": "100", + "outer_l2": { + "dstmac": "00:00:00:00:00:03", + "framesPerSecond": True, + "framesize": {"64B": "100"}, + "srcmac": "00:00:00:00:00:01" + }, + "outer_l3": { + "count": 1024, + "dscp": 0, + "dstip4": "152.16.40.20", + "proto": "udp", + "srcip4": "152.16.100.20", + "ttl": 32 + }, + "outer_l3v6": { + "count": 1024, + "dscp": 0, + "dstip4": "152.16.100.20", + "proto": "udp", + "srcip4": "152.16.40.20", + "ttl": 32 + }, + "outer_l4": { + "dstport": "2001", + "srcport": "1234" + }, + "traffic_type": "continuous" + }, + "downlink_0": { + "id": 2, + "bidir": "False", + "duration": 60, + "iload": "100", + "outer_l2": { + "dstmac": "00:00:00:00:00:04", + "framesPerSecond": True, + "framesize": {"64B": "100"}, + "srcmac": "00:00:00:00:00:01" + }, + "outer_l3": { + "count": 1024, + "dscp": 0, + "dstip4": "152.16.100.20", + "proto": "udp", + "srcip4": "152.16.40.20", + "ttl": 32 + }, + "outer_l3v6": { + "count": 1024, + "dscp": 0, + "dstip4": "152.16.100.20", + "proto": "udp", + "srcip4": "152.16.40.20", + "ttl": 32 + }, + "outer_l4": { + "dstport": "1234", + "srcport": "2001" + }, + "traffic_type": "continuous" + } + } + + ixnet = mock.MagicMock() + ixnet.getList.side_effect = [[1], [1], [1], ["srcIp", "dstIp"]] + ixnet.remapIds.return_value = ["0"] + ixnet.setMultiAttribute.return_value = [1] + ixnet.commit.return_value = [1] + + ixnet_gen = IxNextgen(ixnet) + + result = ixnet_gen.add_ip_header(static_traffic_profile, IP_VERSION_6) + self.assertIsNone(result) + self.assertGreater(ixnet.setMultiAttribute.call_count, 0) + self.assertEqual(ixnet.commit.call_count, 1) + + def test_add_ip_header_v6_nothing_to_do(self): + static_traffic_params = { + "uplink_0": { + "id": 1, + "bidir": "False", + "duration": 60, + "iload": "100", + "outer_l2": { + "dstmac": "00:00:00:00:00:03", + "framesPerSecond": True, + "framesize": {"64B": "100"}, + "srcmac": "00:00:00:00:00:01" + }, + "outer_l3": { + "dscp": 0, + "dstip4": "152.16.40.20", + "proto": "udp", + "srcip4": "152.16.100.20", + "count": 1024, + "ttl": 32 + }, + "outer_l3v6": { + "dscp": 0, + "dstip4": "152.16.40.20", + "proto": "udp", + "srcip4": "152.16.100.20", + "ttl": 32 + }, + "outer_l4": { + "dstport": "2001", + "srcport": "1234" + }, + "traffic_type": "continuous" + }, + "downlink_0": { + "id": 2, + "bidir": "False", + "duration": 60, + "iload": "100", + "outer_l2": { + "dstmac": "00:00:00:00:00:04", + "framesPerSecond": True, + "framesize": {"64B": "100"}, + "srcmac": "00:00:00:00:00:01" + }, + "outer_l3": { + "count": 1024, + "dscp": 0, + "dstip4": "152.16.100.20", + "proto": "udp", + "srcip4": "152.16.40.20", + "ttl": 32 + }, + "outer_l3v6": { + "count": 1024, + "dscp": 0, + "dstip4": "152.16.100.20", + "proto": "udp", + "srcip4": "152.16.40.20", + "ttl": 32 + }, + "outer_l4": { + "dstport": "1234", + "srcport": "2001" + }, + "traffic_type": "continuous" + } + } + + ixnet = mock.MagicMock() + ixnet.getList.side_effect = [[1], [0, 1], [1], ["srcIP", "dstIP"]] + ixnet.remapIds.return_value = ["0"] + ixnet.setMultiAttribute.return_value = [1] + ixnet.commit.return_value = [1] + + ixnet_gen = IxNextgen(ixnet) + + result = ixnet_gen.add_ip_header(static_traffic_params, IP_VERSION_6) + self.assertIsNone(result) + self.assertEqual(ixnet.setMultiAttribute.call_count, 0) + + def test_set_random_ip_multi_attributes_bad_ip_version(self): + bad_ip_version = object() + ixnet_gen = IxNextgen(mock.Mock()) + with self.assertRaises(ValueError): + ixnet_gen.set_random_ip_multi_attributes( + mock.Mock(), bad_ip_version, mock.Mock(), mock.Mock()) + + def test_get_config(self): + tg_cfg = { + "vdu": [ + { + "external-interface": [ + { + "virtual-interface": { + "vpci": "0000:07:00.1", + }, + }, + { + "virtual-interface": { + "vpci": "0001:08:01.2", + }, + }, + ], + }, + ], + "mgmt-interface": { + "ip": "test1", + "tg-config": { + "dut_result_dir": "test2", + "version": "test3", + "ixchassis": "test4", + "tcl_port": "test5", + }, + } + } + + expected = { + 'machine': 'test1', + 'port': 'test5', + 'chassis': 'test4', + 'cards': ['0000', '0001'], + 'ports': ['07', '08'], + 'output_dir': 'test2', + 'version': 'test3', + 'bidir': True, + } + + result = IxNextgen.get_config(tg_cfg) + self.assertDictEqual(result, expected) + + def test_ix_update_ether(self): + static_traffic_params = { + "uplink_0": { + "id": 1, + "bidir": "False", + "duration": 60, + "iload": "100", + "outer_l2": { + "dstmac": "00:00:00:00:00:03", + "framesPerSecond": True, + "framesize": 64, + "srcmac": "00:00:00:00:00:01" + }, + "outer_l3": { + "dscp": 0, + "dstip4": "152.16.40.20", + "proto": "udp", + "srcip4": "152.16.100.20", + "ttl": 32 + }, + "outer_l3v4": { + "dscp": 0, + "dstip4": "152.16.40.20", + "proto": "udp", + "srcip4": "152.16.100.20", + "ttl": 32 + }, + "outer_l3v6": { + "count": 1024, + "dscp": 0, + "dstip4": "152.16.100.20", + "proto": "udp", + "srcip4": "152.16.40.20", + "ttl": 32 + }, + "outer_l4": { + "dstport": "2001", + "srcport": "1234" + }, + "traffic_type": "continuous" + }, + "downlink_0": { + "id": 2, + "bidir": "False", + "duration": 60, + "iload": "100", + "outer_l2": { + "dstmac": "00:00:00:00:00:04", + "framesPerSecond": True, + "framesize": 64, + "srcmac": "00:00:00:00:00:01" + }, + "outer_l3": { + "count": 1024, + "dscp": 0, + "dstip4": "152.16.100.20", + "proto": "udp", + "srcip4": "152.16.40.20", + "ttl": 32 + }, + "outer_l3v4": { + "count": 1024, + "dscp": 0, + "dstip4": "152.16.100.20", + "proto": "udp", + "srcip4": "152.16.40.20", + "ttl": 32 + }, + "outer_l3v6": { + "count": 1024, + "dscp": 0, + "dstip4": "152.16.100.20", + "proto": "udp", + "srcip4": "152.16.40.20", + "ttl": 32 + }, + "outer_l4": { + "dstport": "1234", + "srcport": "2001" + }, + "traffic_type": "continuous" + } + } + + ixnet = mock.MagicMock() + ixnet.setMultiAttribute.return_value = [1] + ixnet.commit.return_value = [1] + ixnet.getList.side_effect = [ + [1], + [1], + [1], + [ + "ethernet.header.destinationAddress", + "ethernet.header.sourceAddress", + ], + ] + + ixnet_gen = IxNextgen(ixnet) + + result = ixnet_gen.ix_update_ether(static_traffic_params) + self.assertIsNone(result) + self.assertGreater(ixnet.setMultiAttribute.call_count, 0) + + def test_ix_update_ether_nothing_to_do(self): + static_traffic_params = { + "uplink_0": { + "id": 1, + "bidir": "False", + "duration": 60, + "iload": "100", + "outer_l3": { + "dscp": 0, + "dstip4": "152.16.40.20", + "proto": "udp", + "srcip4": "152.16.100.20", + "ttl": 32 + }, + "outer_l3v4": { + "dscp": 0, + "dstip4": "152.16.40.20", + "proto": "udp", + "srcip4": "152.16.100.20", + "ttl": 32 + }, + "outer_l3v6": { + "count": 1024, + "dscp": 0, + "dstip4": "152.16.100.20", + "proto": "udp", + "srcip4": "152.16.40.20", + "ttl": 32 + }, + "outer_l4": { + "dstport": "2001", + "srcport": "1234" + }, + "traffic_type": "continuous" + }, + "downlink_0": { + "id": 2, + "bidir": "False", + "duration": 60, + "iload": "100", + "outer_l3": { + "count": 1024, + "dscp": 0, + "dstip4": "152.16.100.20", + "proto": "udp", + "srcip4": "152.16.40.20", + "ttl": 32 + }, + "outer_l3v4": { + "count": 1024, + "dscp": 0, + "dstip4": "152.16.100.20", + "proto": "udp", + "srcip4": "152.16.40.20", + "ttl": 32 + }, + "outer_l3v6": { + "count": 1024, + "dscp": 0, + "dstip4": "152.16.100.20", + "proto": "udp", + "srcip4": "152.16.40.20", + "ttl": 32 + }, + "outer_l4": { + "dstport": "1234", + "srcport": "2001" + }, + "traffic_type": "continuous" + } + } + + ixnet = mock.MagicMock() + ixnet.setMultiAttribute.return_value = [1] + ixnet.commit.return_value = [1] + ixnet.getList.side_effect = [ + [1], + [1], + [1], + [ + "ethernet.header.destinationAddress", + "ethernet.header.sourceAddress", + ], + ] + + ixnet_gen = IxNextgen(ixnet) + + result = ixnet_gen.ix_update_ether(static_traffic_params) + self.assertIsNone(result) + self.assertEqual(ixnet.setMultiAttribute.call_count, 0) diff --git a/yardstick/tests/unit/network_services/test_utils.py b/yardstick/tests/unit/network_services/test_utils.py new file mode 100644 index 000000000..2b2eb7109 --- /dev/null +++ b/yardstick/tests/unit/network_services/test_utils.py @@ -0,0 +1,141 @@ +# Copyright (c) 2016-2017 Intel Corporation +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import os +import unittest +import mock + +from yardstick.network_services import utils + + +class UtilsTestCase(unittest.TestCase): + """Test all VNF helper methods.""" + + DPDK_PATH = os.path.join(utils.NSB_ROOT, "dpdk-devbind.py") + + def setUp(self): + super(UtilsTestCase, self).setUp() + + def test_get_nsb_options(self): + result = utils.get_nsb_option("bin_path", None) + self.assertEqual(result, utils.NSB_ROOT) + + def test_get_nsb_option_is_invalid_key(self): + result = utils.get_nsb_option("bin", None) + self.assertEqual(result, None) + + def test_get_nsb_option_default(self): + default = object() + result = utils.get_nsb_option("nosuch", default) + self.assertIs(result, default) + + def test_provision_tool(self): + with mock.patch("yardstick.ssh.SSH") as ssh: + ssh_mock = mock.Mock(autospec=ssh.SSH) + ssh_mock.execute = \ + mock.Mock(return_value=(0, self.DPDK_PATH, "")) + ssh.return_value = ssh_mock + tool_path = utils.provision_tool(ssh_mock, self.DPDK_PATH) + self.assertEqual(tool_path, self.DPDK_PATH) + + def test_provision_tool_no_path(self): + with mock.patch("yardstick.ssh.SSH") as ssh: + ssh_mock = mock.Mock(autospec=ssh.SSH) + ssh_mock.execute = \ + mock.Mock(return_value=(1, self.DPDK_PATH, "")) + ssh.return_value = ssh_mock + tool_path = utils.provision_tool(ssh_mock, self.DPDK_PATH) + self.assertEqual(tool_path, self.DPDK_PATH) + + +class PciAddressTestCase(unittest.TestCase): + + PCI_ADDRESS_DBSF = '000A:07:03.2' + PCI_ADDRESS_BSF = '06:02.1' + PCI_ADDRESS_DBSF_MULTILINE_1 = '0001:08:04.3\nother text\n' + PCI_ADDRESS_DBSF_MULTILINE_2 = 'first line\n 0001:08:04.3 \nother text\n' + # Will match and return the first address found. + PCI_ADDRESS_DBSF_MULTILINE_3 = ' 0001:08:04.1 \n 05:03.1 \nother\n' + PCI_ADDRESS_BSF_MULTILINE_1 = 'first line\n 08:04.3 \n 0002:05:03.1\n' + BAD_INPUT_1 = 'no address found' + BAD_INPUT_2 = '001:08:04.1' + BAD_INPUT_3 = '08:4.1' + + def test_pciaddress_dbsf(self): + pci_address = utils.PciAddress(PciAddressTestCase.PCI_ADDRESS_DBSF) + self.assertEqual('000a', pci_address.domain) + self.assertEqual('07', pci_address.bus) + self.assertEqual('03', pci_address.slot) + self.assertEqual('2', pci_address.function) + + def test_pciaddress_bsf(self): + pci_address = utils.PciAddress(PciAddressTestCase.PCI_ADDRESS_BSF) + self.assertEqual('0000', pci_address.domain) + self.assertEqual('06', pci_address.bus) + self.assertEqual('02', pci_address.slot) + self.assertEqual('1', pci_address.function) + + def test_pciaddress_dbsf_multiline_1(self): + pci_address = utils.PciAddress( + PciAddressTestCase.PCI_ADDRESS_DBSF_MULTILINE_1) + self.assertEqual('0001', pci_address.domain) + self.assertEqual('08', pci_address.bus) + self.assertEqual('04', pci_address.slot) + self.assertEqual('3', pci_address.function) + + def test_pciaddress_dbsf_multiline_2(self): + pci_address = utils.PciAddress( + PciAddressTestCase.PCI_ADDRESS_DBSF_MULTILINE_2) + self.assertEqual('0001', pci_address.domain) + self.assertEqual('08', pci_address.bus) + self.assertEqual('04', pci_address.slot) + self.assertEqual('3', pci_address.function) + + def test_pciaddress_dbsf_multiline_3(self): + pci_address = utils.PciAddress( + PciAddressTestCase.PCI_ADDRESS_DBSF_MULTILINE_3) + self.assertEqual('0001', pci_address.domain) + self.assertEqual('08', pci_address.bus) + self.assertEqual('04', pci_address.slot) + self.assertEqual('1', pci_address.function) + + def test_pciaddress_bsf_multiline_1(self): + pci_address = utils.PciAddress( + PciAddressTestCase.PCI_ADDRESS_BSF_MULTILINE_1) + self.assertEqual('0000', pci_address.domain) + self.assertEqual('08', pci_address.bus) + self.assertEqual('04', pci_address.slot) + self.assertEqual('3', pci_address.function) + + def test_pciaddress_bad_input_no_address(self): + with self.assertRaises(ValueError) as exception: + utils.PciAddress(PciAddressTestCase.BAD_INPUT_1) + self.assertEqual('Invalid PCI address: {}'.format( + PciAddressTestCase.BAD_INPUT_1), str(exception.exception)) + + def test_pciaddress_bad_input_dbsf_bad_formatted(self): + # In this test case, the domain has only 3 characters instead of 4. + pci_address = utils.PciAddress( + PciAddressTestCase.BAD_INPUT_2) + self.assertEqual('0000', pci_address.domain) + self.assertEqual('08', pci_address.bus) + self.assertEqual('04', pci_address.slot) + self.assertEqual('1', pci_address.function) + + def test_pciaddress_bad_input_bsf_bad_formatted(self): + with self.assertRaises(ValueError) as exception: + utils.PciAddress(PciAddressTestCase.BAD_INPUT_3) + self.assertEqual('Invalid PCI address: {}'.format( + PciAddressTestCase.BAD_INPUT_3), str(exception.exception)) diff --git a/yardstick/tests/unit/network_services/test_yang_model.py b/yardstick/tests/unit/network_services/test_yang_model.py new file mode 100644 index 000000000..a7eb36b8a --- /dev/null +++ b/yardstick/tests/unit/network_services/test_yang_model.py @@ -0,0 +1,129 @@ +# Copyright (c) 2016-2017 Intel Corporation +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import mock +import unittest + +from yardstick.network_services.yang_model import YangModel + + +class YangModelTestCase(unittest.TestCase): + """Test all Yang Model methods.""" + + ENTRIES = { + 'access-list1': { + 'acl': { + 'access-list-entries': [{ + 'ace': { + 'ace-oper-data': { + 'match-counter': 0}, + 'actions': 'drop,count', + 'matches': { + 'destination-ipv4-network': + '152.16.40.20/24', + 'destination-port-range': { + 'lower-port': 0, + 'upper-port': 65535}, + 'source-ipv4-network': '0.0.0.0/0', + 'source-port-range': { + 'lower-port': 0, + 'upper-port': 65535}}, + 'rule-name': 'rule1588'}}, + { + 'ace': { + 'ace-oper-data': { + 'match-counter': 0}, + 'actions': 'drop,count', + 'matches': { + 'destination-ipv4-network': + '0.0.0.0/0', + 'destination-port-range': { + 'lower-port': 0, + 'upper-port': 65535}, + 'source-ipv4-network': + '152.16.100.20/24', + 'source-port-range': { + 'lower-port': 0, + 'upper-port': 65535}}, + 'rule-name': 'rule1589'}}], + 'acl-name': 'sample-ipv4-acl', + 'acl-type': 'ipv4-acl'} + } + } + + def test__init__(self): + cfg = "yang.yaml" + y = YangModel(cfg) + self.assertEqual(y.config_file, cfg) + + def test_config_file_setter(self): + cfg = "yang.yaml" + y = YangModel(cfg) + self.assertEqual(y.config_file, cfg) + cfg2 = "yang2.yaml" + y.config_file = cfg2 + self.assertEqual(y.config_file, cfg2) + + def test__get_entries(self): + cfg = "yang.yaml" + y = YangModel(cfg) + y._options = self.ENTRIES + y._get_entries() + self.assertIn("p acl add", y._rules) + + def test__get_entries_no_options(self): + cfg = "yang.yaml" + y = YangModel(cfg) + y._get_entries() + self.assertEqual(y._rules, '') + + @mock.patch('yardstick.network_services.yang_model.open') + @mock.patch('yardstick.network_services.yang_model.yaml_load') + def test__read_config(self, mock_safe_load, *args): + cfg = "yang.yaml" + y = YangModel(cfg) + mock_safe_load.return_value = expected = {'key1': 'value1', 'key2': 'value2'} + y._read_config() + self.assertDictEqual(y._options, expected) + + @mock.patch('yardstick.network_services.yang_model.open') + def test__read_config_open_error(self, mock_open): + cfg = "yang.yaml" + y = YangModel(cfg) + mock_open.side_effect = IOError('my error') + + self.assertEqual(y._options, {}) + with self.assertRaises(IOError) as raised: + y._read_config() + + self.assertIn('my error', str(raised.exception)) + self.assertEqual(y._options, {}) + + def test_get_rules(self): + cfg = "yang.yaml" + y = YangModel(cfg) + y._read_config = read_mock = mock.Mock() + y._get_entries = get_mock = mock.Mock() + + y._rules = None + self.assertIsNone(y.get_rules()) + self.assertEqual(read_mock.call_count, 1) + self.assertEqual(get_mock.call_count, 1) + + # True value should prevent calling read and get + y._rules = 999 + self.assertEqual(y.get_rules(), 999) + self.assertEqual(read_mock.call_count, 1) + self.assertEqual(get_mock.call_count, 1) diff --git a/yardstick/tests/unit/orchestrator/test_heat.py b/yardstick/tests/unit/orchestrator/test_heat.py index aae2487aa..3ec59a3c2 100644 --- a/yardstick/tests/unit/orchestrator/test_heat.py +++ b/yardstick/tests/unit/orchestrator/test_heat.py @@ -17,6 +17,7 @@ import shade import unittest from yardstick.benchmark.contexts import node +from yardstick.common import constants from yardstick.common import exceptions from yardstick.orchestrator import heat @@ -53,6 +54,14 @@ class HeatStackTestCase(unittest.TestCase): self._mock_stack_get.stop() heat._DEPLOYED_STACKS = {} + @mock.patch.object(shade, 'openstack_cloud') + def test__init(self, mock_openstack_cloud): + os_cloud_config = {'key': 'value'} + heatstack = heat.HeatStack('name', os_cloud_config=os_cloud_config) + self.assertEqual('name', heatstack.name) + os_cloud_config.update(constants.OS_CLOUD_DEFAULT_CONFIG) + mock_openstack_cloud.assert_called_once_with(**os_cloud_config) + def test_create(self): template = {'tkey': 'tval'} heat_parameters = {'pkey': 'pval'} @@ -192,7 +201,9 @@ class HeatStackTestCase(unittest.TestCase): class HeatTemplateTestCase(unittest.TestCase): def setUp(self): - self.template = heat.HeatTemplate('test') + self._os_cloud_config = {'key1': 'value1'} + self.template = heat.HeatTemplate( + 'test', os_cloud_config=self._os_cloud_config) def test_add_tenant_network(self): self.template.add_network('some-network') @@ -337,8 +348,12 @@ class HeatTemplateTestCase(unittest.TestCase): def test_create_not_block(self): heat_stack = mock.Mock() - with mock.patch.object(heat, 'HeatStack', return_value=heat_stack): + with mock.patch.object(heat, 'HeatStack', return_value=heat_stack) \ + as mock_heatstack: ret = self.template.create(block=False) + + mock_heatstack.assert_called_once_with( + self.template.name, os_cloud_config=self.template._os_cloud_config) heat_stack.create.assert_called_once_with( self.template._template, self.template.heat_parameters, False, 3600) @@ -354,13 +369,30 @@ class HeatTemplateTestCase(unittest.TestCase): 3600) self.assertEqual(heat_stack, ret) - def test_create_block_status_no_complete(self): heat_stack = mock.Mock() heat_stack.status = 'other status' + heat_stack.get_failures.return_value = [] with mock.patch.object(heat, 'HeatStack', return_value=heat_stack): self.assertRaises(exceptions.HeatTemplateError, self.template.create, block=True) heat_stack.create.assert_called_once_with( self.template._template, self.template.heat_parameters, True, 3600) + + def test_create_block_status_no_complete_with_reasons(self): + heat_stack = mock.Mock() + heat_stack.status = 'other status' + heat_stack.get_failures.return_value = [ + mock.Mock(resource_status_reason="A reason"), + mock.Mock(resource_status_reason="Something else") + ] + with mock.patch.object(heat, 'HeatStack', return_value=heat_stack): + with mock.patch.object(heat, 'log') as mock_log: + self.assertRaises(exceptions.HeatTemplateError, + self.template.create, block=True) + mock_log.error.assert_any_call("%s", "A reason") + mock_log.error.assert_any_call("%s", "Something else") + heat_stack.create.assert_called_once_with( + self.template._template, self.template.heat_parameters, True, + 3600) |