collectd: write config file from Jinja2 template
[yardstick.git] / yardstick / network_services / vnf_generic / vnf / base.py
1 # Copyright (c) 2016-2017 Intel Corporation
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #      http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 """ Base class implementation for generic vnf implementation """
15
16 from __future__ import absolute_import
17 import logging
18
19 from yardstick.network_services.helpers.samplevnf_helper import PortPairs
20
21 LOG = logging.getLogger(__name__)
22
23
24 class QueueFileWrapper(object):
25     """ Class providing file-like API for talking with SSH connection """
26
27     def __init__(self, q_in, q_out, prompt):
28         self.q_in = q_in
29         self.q_out = q_out
30         self.closed = False
31         self.buf = []
32         self.bufsize = 20
33         self.prompt = prompt
34
35     def read(self, size):
36         """ read chunk from input queue """
37         if self.q_in.qsize() > 0 and size:
38             in_data = self.q_in.get()
39             return in_data
40
41     def write(self, chunk):
42         """ write chunk to output queue """
43         self.buf.append(chunk)
44         # flush on prompt or if we exceed bufsize
45
46         size = sum(len(c) for c in self.buf)
47         if self.prompt in chunk or size > self.bufsize:
48             out = ''.join(self.buf)
49             self.buf = []
50             self.q_out.put(out)
51
52     def close(self):
53         """ close multiprocessing queue """
54         pass
55
56     def clear(self):
57         """ clear queue """
58         while self.q_out.qsize() > 0:
59             self.q_out.get()
60
61
62 class VnfdHelper(dict):
63
64     def __init__(self, *args, **kwargs):
65         super(VnfdHelper, self).__init__(*args, **kwargs)
66         self.port_pairs = PortPairs(self['vdu'][0]['external-interface'])
67
68     @property
69     def mgmt_interface(self):
70         return self["mgmt-interface"]
71
72     @property
73     def vdu(self):
74         return self['vdu']
75
76     @property
77     def vdu0(self):
78         return self.vdu[0]
79
80     @property
81     def interfaces(self):
82         return self.vdu0['external-interface']
83
84     @property
85     def kpi(self):
86         return self['benchmark']['kpi']
87
88     def find_virtual_interface(self, **kwargs):
89         key, value = next(iter(kwargs.items()))
90         for interface in self.interfaces:
91             virtual_intf = interface["virtual-interface"]
92             if virtual_intf[key] == value:
93                 return interface
94
95     def find_interface(self, **kwargs):
96         key, value = next(iter(kwargs.items()))
97         for interface in self.interfaces:
98             if interface[key] == value:
99                 return interface
100
101     # hide dpdk_port_num key so we can abstract
102     def find_interface_by_port(self, port):
103         for interface in self.interfaces:
104             virtual_intf = interface["virtual-interface"]
105             # we have to convert to int to compare
106             if int(virtual_intf['dpdk_port_num']) == port:
107                 return interface
108
109     def port_num(self, port):
110         # we need interface name -> DPDK port num (PMD ID) -> LINK ID
111         # LINK ID -> PMD ID is governed by the port mask
112         """
113
114         :rtype: int
115         :type port: str
116         """
117         if isinstance(port, dict):
118             intf = port
119         else:
120             intf = self.find_interface(name=port)
121         return int(intf["virtual-interface"]["dpdk_port_num"])
122
123     def port_nums(self, intfs):
124         return [self.port_num(i) for i in intfs]
125
126
127 class VNFObject(object):
128
129     # centralize network naming convention
130     UPLINK = PortPairs.UPLINK
131     DOWNLINK = PortPairs.DOWNLINK
132
133     def __init__(self, name, vnfd):
134         super(VNFObject, self).__init__()
135         self.name = name
136         self.vnfd_helper = VnfdHelper(vnfd)  # fixme: parse this into a structure
137
138
139 class GenericVNF(VNFObject):
140
141     """ Class providing file-like API for generic VNF implementation """
142     def __init__(self, name, vnfd):
143         super(GenericVNF, self).__init__(name, vnfd)
144         # List of statistics we can obtain from this VNF
145         # - ETSI MANO 6.3.1.1 monitoring_parameter
146         self.kpi = self._get_kpi_definition()
147         # Standard dictionary containing params like thread no, buffer size etc
148         self.config = {}
149         self.runs_traffic = False
150
151     def _get_kpi_definition(self):
152         """ Get list of KPIs defined in VNFD
153
154         :param vnfd:
155         :return: list of KPIs, e.g. ['throughput', 'latency']
156         """
157         return self.vnfd_helper.kpi
158
159     def instantiate(self, scenario_cfg, context_cfg):
160         """ Prepare VNF for operation and start the VNF process/VM
161
162         :param scenario_cfg:
163         :param context_cfg:
164         :return: True/False
165         """
166         raise NotImplementedError()
167
168     def terminate(self):
169         """ Kill all VNF processes
170
171         :return:
172         """
173         raise NotImplementedError()
174
175     def scale(self, flavor=""):
176         """
177
178         :param flavor:
179         :return:
180         """
181         raise NotImplementedError()
182
183     def collect_kpi(self):
184         """This method should return a dictionary containing the
185         selected KPI at a given point of time.
186
187         :return: {"kpi": value, "kpi2": value}
188         """
189         raise NotImplementedError()
190
191
192 class GenericTrafficGen(GenericVNF):
193     """ Class providing file-like API for generic traffic generator """
194
195     def __init__(self, name, vnfd):
196         super(GenericTrafficGen, self).__init__(name, vnfd)
197         self.runs_traffic = True
198         self.traffic_finished = False
199
200     def run_traffic(self, traffic_profile):
201         """ Generate traffic on the wire according to the given params.
202         Method is non-blocking, returns immediately when traffic process
203         is running. Mandatory.
204
205         :param traffic_profile:
206         :return: True/False
207         """
208         raise NotImplementedError()
209
210     def listen_traffic(self, traffic_profile):
211         """ Listen to traffic with the given parameters.
212         Method is non-blocking, returns immediately when traffic process
213         is running. Optional.
214
215         :param traffic_profile:
216         :return: True/False
217         """
218         pass
219
220     def verify_traffic(self, traffic_profile):
221         """ Verify captured traffic after it has ended. Optional.
222
223         :param traffic_profile:
224         :return: dict
225         """
226         pass
227
228     def terminate(self):
229         """ After this method finishes, all traffic processes should stop. Mandatory.
230
231         :return: True/False
232         """
233         raise NotImplementedError()