Merge "Bug Fix: Start openvswitch service in Centos distro"
[yardstick.git] / yardstick / benchmark / contexts / base.py
1 ##############################################################################
2 # Copyright (c) 2015 Huawei Technologies Co.,Ltd and others.
3 #
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 ##############################################################################
9
10 import abc
11 import six
12
13 from yardstick.common import constants
14 from yardstick.common import utils
15
16
17 class Flags(object):
18     """Class to represent the status of the flags in a context"""
19
20     _FLAGS = {'no_setup': False,
21               'no_teardown': False,
22               'os_cloud_config': constants.OS_CLOUD_DEFAULT_CONFIG}
23
24     def __init__(self, **kwargs):
25         for name, value in self._FLAGS.items():
26             setattr(self, name, value)
27
28         for name, value in ((name, value) for (name, value) in kwargs.items()
29                             if name in self._FLAGS):
30             setattr(self, name, value)
31
32     def parse(self, **kwargs):
33         """Read in values matching the flags stored in this object"""
34         if not kwargs:
35             return
36
37         for name, value in ((name, value) for (name, value) in kwargs.items()
38                             if name in self._FLAGS):
39             setattr(self, name, value)
40
41
42 @six.add_metaclass(abc.ABCMeta)
43 class Context(object):
44     """Class that represents a context in the logical model"""
45     list = []
46     SHORT_TASK_ID_LEN = 8
47
48     @staticmethod
49     def split_name(name, sep='.'):
50         try:
51             name_iter = iter(name.split(sep))
52         except AttributeError:
53             # name is not a string
54             return None, None
55         return next(name_iter), next(name_iter, None)
56
57     def __init__(self):
58         Context.list.append(self)
59         self._flags = Flags()
60         self._name = None
61         self._task_id = None
62
63     def init(self, attrs):
64         """Initiate context"""
65         self._name = attrs['name']
66         self._task_id = attrs['task_id']
67         self._flags.parse(**attrs.get('flags', {}))
68         self._name_task_id = '{}-{}'.format(
69             self._name, self._task_id[:self.SHORT_TASK_ID_LEN])
70
71     @property
72     def name(self):
73         if self._flags.no_setup or self._flags.no_teardown:
74             return self._name
75         else:
76             return self._name_task_id
77
78     @property
79     def assigned_name(self):
80         return self._name
81
82     @staticmethod
83     def get_cls(context_type):
84         """Return class of specified type."""
85         for context in utils.itersubclasses(Context):
86             if context_type == context.__context_type__:
87                 return context
88         raise RuntimeError("No such context_type %s" % context_type)
89
90     @staticmethod
91     def get(context_type):
92         """Returns instance of a context for context type.
93         """
94         return Context.get_cls(context_type)()
95
96     @abc.abstractmethod
97     def deploy(self):
98         """Deploy context."""
99
100     @abc.abstractmethod
101     def undeploy(self):
102         """Undeploy context."""
103         self._delete_context()
104
105     def _delete_context(self):
106         Context.list.remove(self)
107
108     @abc.abstractmethod
109     def _get_server(self, attr_name):
110         """get server info by name from context
111         """
112
113     @abc.abstractmethod
114     def _get_network(self, attr_name):
115         """get network info by name from context
116         """
117
118     @staticmethod
119     def get_server(attr_name):
120         """lookup server info by name from context
121         attr_name: either a name for a server created by yardstick or a dict
122         with attribute name mapping when using external heat templates
123         """
124         servers = (context._get_server(attr_name) for context in Context.list)
125         try:
126             return next(s for s in servers if s)
127         except StopIteration:
128             raise ValueError("context not found for server %r" %
129                              attr_name)
130
131     @staticmethod
132     def get_context_from_server(attr_name):
133         """lookup context info by name from node config
134         attr_name: either a name of the node created by yardstick or a dict
135         with attribute name mapping when using external templates
136
137         :returns Context instance
138         """
139         servers = ((context._get_server(attr_name), context)
140                    for context in Context.list)
141         try:
142             return next(con for s, con in servers if s)
143         except StopIteration:
144             raise ValueError("context not found for name %r" %
145                              attr_name)
146
147     @staticmethod
148     def get_network(attr_name):
149         """lookup server info by name from context
150         attr_name: either a name for a server created by yardstick or a dict
151         with attribute name mapping when using external heat templates
152         """
153
154         networks = (context._get_network(attr_name) for context in Context.list)
155         try:
156             return next(n for n in networks if n)
157         except StopIteration:
158             raise ValueError("context not found for server %r" %
159                              attr_name)