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