Merge "Adding new test case for prox Standalone L3FWD."
[yardstick.git] / yardstick / benchmark / contexts / base.py
index c9b5b51..f3f5879 100644 (file)
 # which accompanies this distribution, and is available at
 # http://www.apache.org/licenses/LICENSE-2.0
 ##############################################################################
-from __future__ import absolute_import
+
 import abc
+import errno
 import six
+import os
+
+from yardstick.common import constants
+from yardstick.common import utils
+from yardstick.common import yaml_loader
+from yardstick.common.constants import YARDSTICK_ROOT_PATH
+
+
+class Flags(object):
+    """Class to represent the status of the flags in a context"""
+
+    _FLAGS = {'no_setup': False,
+              'no_teardown': False,
+              'os_cloud_config': constants.OS_CLOUD_DEFAULT_CONFIG}
+
+    def __init__(self, **kwargs):
+        for name, value in self._FLAGS.items():
+            setattr(self, name, value)
+
+        for name, value in ((name, value) for (name, value) in kwargs.items()
+                            if name in self._FLAGS):
+            setattr(self, name, value)
 
-import yardstick.common.utils as utils
+    def parse(self, **kwargs):
+        """Read in values matching the flags stored in this object"""
+        if not kwargs:
+            return
+
+        for name, value in ((name, value) for (name, value) in kwargs.items()
+                            if name in self._FLAGS):
+            setattr(self, name, value)
 
 
 @six.add_metaclass(abc.ABCMeta)
 class Context(object):
     """Class that represents a context in the logical model"""
     list = []
+    SHORT_TASK_ID_LEN = 8
 
-    @staticmethod
-    def split_name(name, sep='.'):
-        try:
-            name_iter = iter(name.split(sep))
-        except AttributeError:
-            # name is not a string
-            return None, None
-        return next(name_iter), next(name_iter, None)
-
-    def __init__(self):
+    def __init__(self, host_name_separator='.'):
         Context.list.append(self)
+        self._flags = Flags()
+        self._name = None
+        self._task_id = None
+        self.file_path = None
+        self._host_name_separator = host_name_separator
 
-    @abc.abstractmethod
     def init(self, attrs):
-        """Initiate context."""
+        """Initiate context"""
+        self._name = attrs['name']
+        self._task_id = attrs['task_id']
+        self._flags.parse(**attrs.get('flags', {}))
+        self._name_task_id = '{}-{}'.format(
+            self._name, self._task_id[:self.SHORT_TASK_ID_LEN])
+
+    def split_host_name(self, name):
+        if (isinstance(name, six.string_types)
+                and self._host_name_separator in name):
+            return tuple(name.split(self._host_name_separator, 1))
+        return None, None
+
+    def read_pod_file(self, attrs):
+        self.file_path = file_path = attrs.get("file", "pod.yaml")
+        try:
+            cfg = yaml_loader.read_yaml_file(self.file_path)
+        except IOError as io_error:
+            if io_error.errno != errno.ENOENT:
+                raise
+
+            self.file_path = os.path.join(YARDSTICK_ROOT_PATH, file_path)
+            cfg = yaml_loader.read_yaml_file(self.file_path)
+
+        for node in cfg["nodes"]:
+            node["ctx_type"] = self.__context_type__
+
+        self.nodes.extend(cfg["nodes"])
+        self.controllers.extend([node for node in cfg["nodes"]
+                                 if node.get("role") == "Controller"])
+        self.computes.extend([node for node in cfg["nodes"]
+                              if node.get("role") == "Compute"])
+        self.baremetals.extend([node for node in cfg["nodes"]
+                                if node.get("role") == "Baremetal"])
+        return cfg
+
+    @property
+    def name(self):
+        if self._flags.no_setup or self._flags.no_teardown:
+            return self._name
+        else:
+            return self._name_task_id
+
+    @property
+    def assigned_name(self):
+        return self._name
+
+    @property
+    def host_name_separator(self):
+        return self._host_name_separator
 
     @staticmethod
     def get_cls(context_type):
@@ -83,6 +158,25 @@ class Context(object):
             raise ValueError("context not found for server %r" %
                              attr_name)
 
+    @staticmethod
+    def get_physical_nodes():
+        """return physical node names for all contexts"""
+        physical_nodes = {}
+        for context in Context.list:
+            nodes = context._get_physical_nodes()
+            physical_nodes.update({context._name: nodes})
+
+        return physical_nodes
+
+    @staticmethod
+    def get_physical_node_from_server(server_name):
+        """return physical nodes for all contexts"""
+        context = Context.get_context_from_server(server_name)
+        if context == None:
+            return  None
+
+        return context._get_physical_node_for_server(server_name)
+
     @staticmethod
     def get_context_from_server(attr_name):
         """lookup context info by name from node config
@@ -112,3 +206,15 @@ class Context(object):
         except StopIteration:
             raise ValueError("context not found for server %r" %
                              attr_name)
+
+    @abc.abstractmethod
+    def _get_physical_nodes(self):
+        """return the list of physical nodes in context"""
+
+    @abc.abstractmethod
+    def _get_physical_node_for_server(self, server_name):
+        """ Find physical node for given server
+
+        :param server_name: (string) Server name in scenario
+        :return string:  <node_name>.<context_name>
+        """