aboutsummaryrefslogtreecommitdiffstats
path: root/yardstick/network_services/vnf_generic/vnf/base.py
blob: 2df6037f36274f7f8b5d1397d7ec7bb3ec4fa36a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
# Copyright (c) 2016-2017 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""" Base class implementation for generic vnf implementation """

from __future__ import absolute_import
import logging
import ipaddress
import six

from yardstick.network_services.utils import get_nsb_option

LOG = logging.getLogger(__name__)


class QueueFileWrapper(object):
    """ Class providing file-like API for talking with SSH connection """

    def __init__(self, q_in, q_out, prompt):
        self.q_in = q_in
        self.q_out = q_out
        self.closed = False
        self.buf = []
        self.bufsize = 20
        self.prompt = prompt

    def read(self, size):
        """ read chunk from input queue """
        if self.q_in.qsize() > 0 and size:
            in_data = self.q_in.get()
            return in_data

    def write(self, chunk):
        """ write chunk to output queue """
        self.buf.append(chunk)
        # flush on prompt or if we exceed bufsize

        size = sum(len(c) for c in self.buf)
        if self.prompt in chunk or size > self.bufsize:
            out = ''.join(self.buf)
            self.buf = []
            self.q_out.put(out)

    def close(self):
        """ close multiprocessing queue """
        pass

    def clear(self):
        """ clear queue """
        while self.q_out.qsize() > 0:
            self.q_out.get()


class GenericVNF(object):
    """ Class providing file-like API for generic VNF implementation """
    def __init__(self, vnfd):
        super(GenericVNF, self).__init__()
        self.vnfd = vnfd  # fixme: parse this into a structure
        # List of statistics we can obtain from this VNF
        # - ETSI MANO 6.3.1.1 monitoring_parameter
        self.kpi = self._get_kpi_definition(vnfd)
        # Standard dictionary containing params like thread no, buffer size etc
        self.config = {}
        self.runs_traffic = False
        self.name = "vnf__1"  # name in topology file
        self.bin_path = get_nsb_option("bin_path", "")

    @classmethod
    def _get_kpi_definition(cls, vnfd):
        """ Get list of KPIs defined in VNFD

        :param vnfd:
        :return: list of KPIs, e.g. ['throughput', 'latency']
        """
        return vnfd['benchmark']['kpi']

    @classmethod
    def get_ip_version(cls, ip_addr):
        """ get ip address version v6 or v4 """
        try:
            address = ipaddress.ip_address(six.text_type(ip_addr))
        except ValueError:
            LOG.error(ip_addr, " is not valid")
            return
        else:
            return address.version

    def _ip_to_hex(self, ip_addr):
        ip_x = ip_addr
        if self.get_ip_version(ip_addr) == 4:
            ip_to_convert = ip_addr.split(".")
            ip_octect = [int(octect) for octect in ip_to_convert]
            ip_x = "{0[0]:02X}{0[1]:02X}{0[2]:02X}{0[3]:02X}".format(ip_octect)
        return ip_x

    def _get_dpdk_port_num(self, name):
        for intf in self.vnfd['vdu'][0]['external-interface']:
            if name == intf['name']:
                return intf['virtual-interface']['dpdk_port_num']

    def _append_routes(self, ip_pipeline_cfg):
        if 'routing_table' in self.vnfd['vdu'][0]:
            routing_table = self.vnfd['vdu'][0]['routing_table']

            where = ip_pipeline_cfg.find("arp_route_tbl")
            link = ip_pipeline_cfg[:where]
            route_add = ip_pipeline_cfg[where:]

            tmp = route_add.find('\n')
            route_add = route_add[tmp:]

            cmds = "arp_route_tbl ="

            for route in routing_table:
                net = self._ip_to_hex(route['network'])
                net_nm = self._ip_to_hex(route['netmask'])
                net_gw = self._ip_to_hex(route['gateway'])
                port = self._get_dpdk_port_num(route['if'])
                cmd = \
                    " ({port0_local_ip_hex},{port0_netmask_hex},{dpdk_port},"\
                    "{port1_local_ip_hex})".format(port0_local_ip_hex=net,
                                                   port0_netmask_hex=net_nm,
                                                   dpdk_port=port,
                                                   port1_local_ip_hex=net_gw)
                cmds += cmd

            cmds += '\n'
            ip_pipeline_cfg = link + cmds + route_add

        return ip_pipeline_cfg

    def _append_nd_routes(self, ip_pipeline_cfg):
        if 'nd_route_tbl' in self.vnfd['vdu'][0]:
            routing_table = self.vnfd['vdu'][0]['nd_route_tbl']

            where = ip_pipeline_cfg.find("nd_route_tbl")
            link = ip_pipeline_cfg[:where]
            route_nd = ip_pipeline_cfg[where:]

            tmp = route_nd.find('\n')
            route_nd = route_nd[tmp:]

            cmds = "nd_route_tbl ="

            for route in routing_table:
                net = route['network']
                net_nm = route['netmask']
                net_gw = route['gateway']
                port = self._get_dpdk_port_num(route['if'])
                cmd = \
                    " ({port0_local_ip_hex},{port0_netmask_hex},{dpdk_port},"\
                    "{port1_local_ip_hex})".format(port0_local_ip_hex=net,
                                                   port0_netmask_hex=net_nm,
                                                   dpdk_port=port,
                                                   port1_local_ip_hex=net_gw)
                cmds += cmd

            cmds += '\n'
            ip_pipeline_cfg = link + cmds + route_nd

        return ip_pipeline_cfg

    def _get_port0localip6(self):
        return_value = ""
        if 'nd_route_tbl' in self.vnfd['vdu'][0]:
            routing_table = self.vnfd['vdu'][0]['nd_route_tbl']

            inc = 0
            for route in routing_table:
                inc += 1
                if inc == 1:
                    return_value = route['network']
        LOG.info("_get_port0localip6 : %s", return_value)
        return return_value

    def _get_port1localip6(self):
        return_value = ""
        if 'nd_route_tbl' in self.vnfd['vdu'][0]:
            routing_table = self.vnfd['vdu'][0]['nd_route_tbl']

            inc = 0
            for route in routing_table:
                inc += 1
                if inc == 2:
                    return_value = route['network']
        LOG.info("_get_port1localip6 : %s", return_value)
        return return_value

    def _get_port0prefixlen6(self):
        return_value = ""
        if 'nd_route_tbl' in self.vnfd['vdu'][0]:
            routing_table = self.vnfd['vdu'][0]['nd_route_tbl']

            inc = 0
            for route in routing_table:
                inc += 1
                if inc == 1:
                    return_value = route['netmask']
        LOG.info("_get_port0prefixlen6 : %s", return_value)
        return return_value

    def _get_port1prefixlen6(self):
        return_value = ""
        if 'nd_route_tbl' in self.vnfd['vdu'][0]:
            routing_table = self.vnfd['vdu'][0]['nd_route_tbl']

            inc = 0
            for route in routing_table:
                inc += 1
                if inc == 2:
                    return_value = route['netmask']
        LOG.info("_get_port1prefixlen6 : %s", return_value)
        return return_value

    def _get_port0gateway6(self):
        return_value = ""
        if 'nd_route_tbl' in self.vnfd['vdu'][0]:
            routing_table = self.vnfd['vdu'][0]['nd_route_tbl']

            inc = 0
            for route in routing_table:
                inc += 1
                if inc == 1:
                    return_value = route['network']
        LOG.info("_get_port0gateway6 : %s", return_value)
        return return_value

    def _get_port1gateway6(self):
        return_value = ""
        if 'nd_route_tbl' in self.vnfd['vdu'][0]:
            routing_table = self.vnfd['vdu'][0]['nd_route_tbl']

            inc = 0
            for route in routing_table:
                inc += 1
                if inc == 2:
                    return_value = route['network']
        LOG.info("_get_port1gateway6 : %s", return_value)
        return return_value

    def instantiate(self, scenario_cfg, context_cfg):
        """ Prepare VNF for operation and start the VNF process/VM

        :param scenario_cfg:
        :param context_cfg:
        :return: True/False
        """
        raise NotImplementedError()

    def terminate(self):
        """ Kill all VNF processes

        :return:
        """
        raise NotImplementedError()

    def scale(self, flavor=""):
        """

        :param flavor:
        :return:
        """
        raise NotImplementedError()

    def collect_kpi(self):
        """This method should return a dictionary containing the
        selected KPI at a given point of time.

        :return: {"kpi": value, "kpi2": value}
        """
        raise NotImplementedError()


class GenericTrafficGen(GenericVNF):
    """ Class providing file-like API for generic traffic generator """

    def __init__(self, vnfd):
        super(GenericTrafficGen, self).__init__(vnfd)
        self.runs_traffic = True
        self.traffic_finished = False
        self.name = "tgen__1"  # name in topology file

    def run_traffic(self, traffic_profile):
        """ Generate traffic on the wire according to the given params.
        Method is non-blocking, returns immediately when traffic process
        is running. Mandatory.

        :param traffic_profile:
        :return: True/False
        """
        raise NotImplementedError()

    def listen_traffic(self, traffic_profile):
        """ Listen to traffic with the given parameters.
        Method is non-blocking, returns immediately when traffic process
        is running. Optional.

        :param traffic_profile:
        :return: True/False
        """
        pass

    def verify_traffic(self, traffic_profile):
        """ Verify captured traffic after it has ended. Optional.

        :param traffic_profile:
        :return: dict
        """
        pass

    def terminate(self):
        """ After this method finishes, all traffic processes should stop. Mandatory.

        :return: True/False
        """
        raise NotImplementedError()