Merge "Deprecate authentication variable OS_TENANT_NAME"
[yardstick.git] / yardstick / network_services / vnf_generic / vnf / sample_vnf.py
index 20e5895..2009303 100644 (file)
 # limitations under the License.
 """ Base class implementation for generic vnf implementation """
 
-from __future__ import absolute_import
-
-import posixpath
-import time
+from collections import Mapping
 import logging
+from multiprocessing import Queue, Value, Process
 import os
+import posixpath
 import re
 import subprocess
-from collections import Mapping
-from multiprocessing import Queue, Value, Process
+import time
 
+import six
 from six.moves import cStringIO
 
+from trex_stl_lib.trex_stl_client import LoggerApi
+from trex_stl_lib.trex_stl_client import STLClient
+from trex_stl_lib.trex_stl_exceptions import STLError
 from yardstick.benchmark.contexts.base import Context
 from yardstick.benchmark.scenarios.networking.vnf_generic import find_relative_file
+from yardstick.common import exceptions as y_exceptions
+from yardstick.common import utils
 from yardstick.common.process import check_if_process_failed
+from yardstick.network_services.helpers.dpdkbindnic_helper import DpdkBindHelper
 from yardstick.network_services.helpers.samplevnf_helper import PortPairs
 from yardstick.network_services.helpers.samplevnf_helper import MultiPortConfig
-from yardstick.network_services.helpers.dpdkbindnic_helper import DpdkBindHelper
 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 GenericVNF
-from yardstick.network_services.vnf_generic.vnf.base import QueueFileWrapper
 from yardstick.network_services.vnf_generic.vnf.base import GenericTrafficGen
-from yardstick.network_services.utils import get_nsb_option
-
-from trex_stl_lib.trex_stl_client import STLClient
-from trex_stl_lib.trex_stl_client import LoggerApi
-from trex_stl_lib.trex_stl_exceptions import STLError
-
+from yardstick.network_services.vnf_generic.vnf.base import QueueFileWrapper
 from yardstick.ssh import AutoConnectSSH
 
+
 DPDK_VERSION = "dpdk-16.07"
 
 LOG = logging.getLogger(__name__)
@@ -122,6 +122,8 @@ 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):
@@ -158,19 +160,16 @@ class DpdkVnfSetupEnvHelper(SetupEnvHelper):
         self.dpdk_bind_helper = DpdkBindHelper(ssh_helper)
 
     def _setup_hugepages(self):
-        cmd = "awk '/Hugepagesize/ { print $2$3 }' < /proc/meminfo"
-        hugepages = self.ssh_helper.execute(cmd)[1].rstrip()
-
-        memory_path = \
-            '/sys/kernel/mm/hugepages/hugepages-%s/nr_hugepages' % hugepages
-        self.ssh_helper.execute("awk -F: '{ print $1 }' < %s" % memory_path)
-
-        if hugepages == "2048kB":
-            pages = 8192
-        else:
-            pages = 16
-
-        self.ssh_helper.execute("echo %s | sudo tee %s" % (pages, memory_path))
+        meminfo = utils.read_meminfo(self.ssh_helper)
+        hp_size_kb = int(meminfo['Hugepagesize'])
+        nr_hugepages = int(abs(self.HUGEPAGES_KB / hp_size_kb))
+        self.ssh_helper.execute('echo %s | sudo tee %s' %
+                                (nr_hugepages, self.NR_HUGEPAGES_PATH))
+        hp = six.BytesIO()
+        self.ssh_helper.get_file_obj(self.NR_HUGEPAGES_PATH, hp)
+        nr_hugepages_set = int(hp.getvalue().decode('utf-8').splitlines()[0])
+        LOG.info('Hugepages size (kB): %s, number claimed: %s, number set: %s',
+                 hp_size_kb, nr_hugepages, nr_hugepages_set)
 
     def build_config(self):
         vnf_cfg = self.scenario_helper.vnf_cfg
@@ -253,20 +252,12 @@ class DpdkVnfSetupEnvHelper(SetupEnvHelper):
         self.ssh_helper.execute("sudo killall %s" % self.APP_NAME)
 
     def _setup_dpdk(self):
-        """ setup dpdk environment needed for vnf to run """
-
+        """Setup DPDK environment needed for VNF to run"""
         self._setup_hugepages()
-        self.ssh_helper.execute("sudo modprobe uio && sudo modprobe igb_uio")
-
-        exit_status = self.ssh_helper.execute("lsmod | grep -i igb_uio")[0]
-        if exit_status == 0:
-            return
-
-        dpdk = self.ssh_helper.join_bin_path(DPDK_VERSION)
-        dpdk_setup = self.ssh_helper.provision_tool(tool_file="nsb_setup.sh")
-        exit_status = self.ssh_helper.execute("which {} >/dev/null 2>&1".format(dpdk))[0]
-        if exit_status != 0:
-            self.ssh_helper.execute("bash %s dpdk >/dev/null 2>&1" % dpdk_setup)
+        self.ssh_helper.execute('sudo modprobe uio && sudo modprobe igb_uio')
+        exit_status = self.ssh_helper.execute('lsmod | grep -i igb_uio')[0]
+        if exit_status:
+            raise y_exceptions.DPDKSetupDriverError()
 
     def get_collectd_options(self):
         options = self.scenario_helper.all_options.get("collectd", {})
@@ -308,7 +299,7 @@ class DpdkVnfSetupEnvHelper(SetupEnvHelper):
                             if vpci == v['virtual-interface']['vpci'])
                 # force to int
                 intf['virtual-interface']['dpdk_port_num'] = int(dpdk_port_num)
-            except:
+            except:  # pylint: disable=bare-except
                 pass
         time.sleep(2)
 
@@ -345,7 +336,7 @@ class ResourceHelper(object):
 
     def _collect_resource_kpi(self):
         result = {}
-        status = self.resource.check_if_sa_running("collectd")[0]
+        status = self.resource.check_if_system_agent_running("collectd")[0]
         if status == 0:
             result = self.resource.amqp_collect_nfvi_kpi()
 
@@ -472,6 +463,11 @@ class ClientResourceHelper(ResourceHelper):
         self.client.clear_stats(ports=ports)
 
     def start(self, ports=None, *args, **kwargs):
+        # pylint: disable=keyword-arg-before-vararg
+        # NOTE(ralonsoh): defining keyworded arguments before variable
+        # positional arguments is a bug. This function definition doesn't work
+        # in Python 2, although it works in Python 3. Reference:
+        # https://www.python.org/dev/peps/pep-3102/
         if ports is None:
             ports = self.all_ports
         self.client.start(ports=ports, *args, **kwargs)
@@ -480,8 +476,8 @@ class ClientResourceHelper(ResourceHelper):
         if not self._queue.empty():
             kpi = self._queue.get()
             self._result.update(kpi)
-            LOG.debug("Got KPIs from _queue for {0} {1}".format(
-                self.scenario_helper.name, self.RESOURCE_WORD))
+            LOG.debug('Got KPIs from _queue for %s %s',
+                      self.scenario_helper.name, self.RESOURCE_WORD)
         return self._result
 
     def _connect(self, client=None):
@@ -670,7 +666,7 @@ class SampleVNF(GenericVNF):
         self.pipeline_kwargs = {}
         self.uplink_ports = None
         self.downlink_ports = None
-        # TODO(esm): make QueueFileWrapper invert-able so that we
+        # NOTE(esm): make QueueFileWrapper invert-able so that we
         #            never have to manage the queues
         self.q_in = Queue()
         self.q_out = Queue()
@@ -751,7 +747,7 @@ class SampleVNF(GenericVNF):
             if not self._vnf_process.is_alive():
                 raise RuntimeError("%s VNF process died." % self.APP_NAME)
 
-            # TODO(esm): move to QueueFileWrapper
+            # NOTE(esm): move to QueueFileWrapper
             while self.q_out.qsize() > 0:
                 buf.append(self.q_out.get())
                 message = ''.join(buf)
@@ -821,12 +817,12 @@ class SampleVNF(GenericVNF):
             self._vnf_process.terminate()
         # no terminate children here because we share processes with tg
 
-    def get_stats(self, *args, **kwargs):
-        """
-        Method for checking the statistics
+    def get_stats(self, *args, **kwargs):  # pylint: disable=unused-argument
+        """Method for checking the statistics
+
+        This method could be overridden in children classes.
 
-        :return:
-           VNF statistics
+        :return: VNF statistics
         """
         cmd = 'p {0} stats'.format(self.APP_WORD)
         out = self.vnf_execute(cmd)
@@ -849,6 +845,11 @@ class SampleVNF(GenericVNF):
         LOG.debug("%s collect KPIs %s", self.APP_NAME, result)
         return result
 
+    def scale(self, flavor=""):
+        """The SampleVNF base class doesn't provide the 'scale' feature"""
+        raise y_exceptions.FunctionNotImplemented(
+            function_name='scale', class_name='SampleVNFTrafficGen')
+
 
 class SampleVNFTrafficGen(GenericTrafficGen):
     """ Class providing file-like API for generic traffic generator """
@@ -964,3 +965,8 @@ class SampleVNFTrafficGen(GenericTrafficGen):
             self._tg_process.join(PROCESS_JOIN_TIMEOUT)
             self._tg_process.terminate()
         # no terminate children here because we share processes with vnf
+
+    def scale(self, flavor=""):
+        """A traffic generator VFN doesn't provide the 'scale' feature"""
+        raise y_exceptions.FunctionNotImplemented(
+            function_name='scale', class_name='SampleVNFTrafficGen')