Merge "Update virtualenv installation step in userguide"
[yardstick.git] / yardstick / network_services / vnf_generic / vnf / tg_rfc2544_trex.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 """ Trex traffic generation definitions which implements rfc2544 """
15
16 from __future__ import absolute_import
17 from __future__ import print_function
18 import multiprocessing
19 import time
20 import logging
21 import os
22 import yaml
23
24 from yardstick import ssh
25 from yardstick.network_services.vnf_generic.vnf.base import GenericTrafficGen
26 from yardstick.network_services.utils import get_nsb_option
27 from stl.trex_stl_lib.trex_stl_client import STLClient
28 from stl.trex_stl_lib.trex_stl_client import LoggerApi
29 from stl.trex_stl_lib.trex_stl_exceptions import STLError
30
31 LOGGING = logging.getLogger(__name__)
32
33 DURATION = 30
34 WAIT_TIME = 3
35 TREX_SYNC_PORT = 4500
36 TREX_ASYNC_PORT = 4501
37
38
39 class TrexTrafficGenRFC(GenericTrafficGen):
40     """
41     This class handles mapping traffic profile and generating
42     traffic for rfc2544 testcase.
43     """
44
45     def __init__(self, vnfd):
46         super(TrexTrafficGenRFC, self).__init__(vnfd)
47         self._result = {}
48         self._terminated = multiprocessing.Value('i', 0)
49         self._queue = multiprocessing.Queue()
50         self._terminated = multiprocessing.Value('i', 0)
51         self._traffic_process = None
52         self._vpci_ascending = None
53         self.tc_file_name = None
54         self.client = None
55         self.my_ports = None
56
57         mgmt_interface = self.vnfd["mgmt-interface"]
58
59         self.connection = ssh.SSH.from_node(mgmt_interface)
60         self.connection.wait()
61
62     @classmethod
63     def _split_mac_address_into_list(cls, mac):
64         octets = mac.split(':')
65         for i, elem in enumerate(octets):
66             octets[i] = "0x" + str(elem)
67         return octets
68
69     def _generate_trex_cfg(self, vnfd):
70         """
71
72         :param vnfd: vnfd.yaml
73         :return: trex_cfg.yaml file
74         """
75         trex_cfg = dict(
76             port_limit=0,
77             version='2',
78             interfaces=[],
79             port_info=list(dict(
80             ))
81         )
82         trex_cfg["port_limit"] = len(vnfd["vdu"][0]["external-interface"])
83         trex_cfg["version"] = '2'
84
85         cfg_file = []
86         vpci = []
87         port = {}
88
89         ext_intf = vnfd["vdu"][0]["external-interface"]
90         for interface in ext_intf:
91             virt_intf = interface["virtual-interface"]
92             vpci.append(virt_intf["vpci"])
93
94             port["src_mac"] = \
95                 self._split_mac_address_into_list(virt_intf["local_mac"])
96
97             time.sleep(WAIT_TIME)
98             port["dest_mac"] = \
99                 self._split_mac_address_into_list(virt_intf["dst_mac"])
100             if virt_intf["dst_mac"]:
101                 trex_cfg["port_info"].append(port.copy())
102
103         trex_cfg["interfaces"] = vpci
104         cfg_file.append(trex_cfg)
105
106         with open('/tmp/trex_cfg.yaml', 'w') as outfile:
107             outfile.write(yaml.safe_dump(cfg_file, default_flow_style=False))
108         self.connection.put('/tmp/trex_cfg.yaml', '/etc')
109
110         self._vpci_ascending = sorted(vpci)
111
112     def scale(self, flavor=""):
113         ''' scale vnfbased on flavor input '''
114         super(TrexTrafficGenRFC, self).scale(flavor)
115
116     def instantiate(self, scenario_cfg, context_cfg):
117         self._generate_trex_cfg(self.vnfd)
118         self.tc_file_name = '{0}.yaml'.format(scenario_cfg['tc'])
119         trex = os.path.join(self.bin_path, "trex")
120         err, _, _ = \
121             self.connection.execute("ls {} >/dev/null 2>&1".format(trex))
122         if err != 0:
123             self.connection.put(trex, trex, True)
124
125         LOGGING.debug("Starting TRex server...")
126         _tg_server = \
127             multiprocessing.Process(target=self._start_server)
128         _tg_server.start()
129         while True:
130             LOGGING.info("Waiting for TG Server to start.. ")
131             time.sleep(WAIT_TIME)
132
133             status = \
134                 self.connection.execute("lsof -i:%s" % TREX_SYNC_PORT)[0]
135             if status == 0:
136                 LOGGING.info("TG server is up and running.")
137                 return _tg_server.exitcode
138             if not _tg_server.is_alive():
139                 raise RuntimeError("Traffic Generator process died.")
140
141     def listen_traffic(self, traffic_profile):
142         pass
143
144     def _get_logical_if_name(self, vpci):
145         ext_intf = self.vnfd["vdu"][0]["external-interface"]
146         for interface in range(len(self.vnfd["vdu"][0]["external-interface"])):
147             virtual_intf = ext_intf[interface]["virtual-interface"]
148             if virtual_intf["vpci"] == vpci:
149                 return ext_intf[interface]["name"]
150
151     def run_traffic(self, traffic_profile,
152                     client_started=multiprocessing.Value('i', 0)):
153
154         self._traffic_process = \
155             multiprocessing.Process(target=self._traffic_runner,
156                                     args=(traffic_profile, self._queue,
157                                           client_started, self._terminated))
158         self._traffic_process.start()
159         # Wait for traffic process to start
160         while client_started.value == 0:
161             time.sleep(1)
162
163         return self._traffic_process.is_alive()
164
165     def _start_server(self):
166         mgmt_interface = self.vnfd["mgmt-interface"]
167
168         _server = ssh.SSH.from_node(mgmt_interface)
169         _server.wait()
170
171         _server.execute("fuser -n tcp %s %s -k > /dev/null 2>&1" %
172                         (TREX_SYNC_PORT, TREX_ASYNC_PORT))
173         _server.execute("pkill -9 rex > /dev/null 2>&1")
174
175         trex_path = os.path.join(self.bin_path, "trex/scripts")
176         path = get_nsb_option("trex_path", trex_path)
177         trex_cmd = "cd " + path + "; sudo ./t-rex-64 -i > /dev/null 2>&1"
178
179         _server.execute(trex_cmd)
180
181     def _connect_client(self, client=None):
182         if client is None:
183             client = STLClient(username=self.vnfd["mgmt-interface"]["user"],
184                                server=self.vnfd["mgmt-interface"]["ip"],
185                                verbose_level=LoggerApi.VERBOSE_QUIET)
186         for idx in range(6):
187             try:
188                 client.connect()
189                 break
190             except STLError:
191                 LOGGING.info("Unable to connect to Trex. Attempt %s", idx)
192                 time.sleep(WAIT_TIME)
193         return client
194
195     @classmethod
196     def _get_rfc_tolerance(cls, tc_yaml):
197         tolerance = '0.8 - 1.0'
198         if 'tc_options' in tc_yaml['scenarios'][0]:
199             tc_options = tc_yaml['scenarios'][0]['tc_options']
200             if 'rfc2544' in tc_options:
201                 tolerance = \
202                     tc_options['rfc2544'].get('allowed_drop_rate', '0.8 - 1.0')
203
204         tolerance = tolerance.split('-')
205         min_tol = float(tolerance[0])
206         if len(tolerance) == 2:
207             max_tol = float(tolerance[1])
208         else:
209             max_tol = float(tolerance[0])
210
211         return [min_tol, max_tol]
212
213     def _traffic_runner(self, traffic_profile, queue,
214                         client_started, terminated):
215         LOGGING.info("Starting TRex client...")
216         tc_yaml = {}
217
218         with open(self.tc_file_name) as tc_file:
219             tc_yaml = yaml.load(tc_file.read())
220
221         tolerance = self._get_rfc_tolerance(tc_yaml)
222
223         # fixme: fix passing correct trex config file,
224         # instead of searching the default path
225         self.my_ports = [0, 1]
226         self.client = self._connect_client()
227         self.client.reset(ports=self.my_ports)
228         self.client.remove_all_streams(self.my_ports)  # remove all streams
229         while not terminated.value:
230             traffic_profile.execute(self)
231             client_started.value = 1
232             time.sleep(DURATION)
233             self.client.stop(self.my_ports)
234             time.sleep(WAIT_TIME)
235             last_res = self.client.get_stats(self.my_ports)
236             samples = {}
237             for vpci_idx in range(len(self._vpci_ascending)):
238                 name = \
239                     self._get_logical_if_name(self._vpci_ascending[vpci_idx])
240                 # fixme: VNFDs KPIs values needs to be mapped to TRex structure
241                 if not isinstance(last_res, dict):
242                     terminated.value = 1
243                     last_res = {}
244
245                 samples[name] = \
246                     {"rx_throughput_fps":
247                      float(last_res.get(vpci_idx, {}).get("rx_pps", 0.0)),
248                      "tx_throughput_fps":
249                      float(last_res.get(vpci_idx, {}).get("tx_pps", 0.0)),
250                      "rx_throughput_mbps":
251                      float(last_res.get(vpci_idx, {}).get("rx_bps", 0.0)),
252                      "tx_throughput_mbps":
253                      float(last_res.get(vpci_idx, {}).get("tx_bps", 0.0)),
254                      "in_packets":
255                      last_res.get(vpci_idx, {}).get("ipackets", 0),
256                      "out_packets":
257                      last_res.get(vpci_idx, {}).get("opackets", 0)}
258
259             samples = \
260                 traffic_profile.get_drop_percentage(self, samples,
261                                                     tolerance[0], tolerance[1])
262             queue.put(samples)
263         self.client.stop(self.my_ports)
264         self.client.disconnect()
265         queue.put(samples)
266
267     def collect_kpi(self):
268         if not self._queue.empty():
269             result = self._queue.get()
270             self._result.update(result)
271         LOGGING.debug("trex collect Kpis %s", self._result)
272         return self._result
273
274     def terminate(self):
275         self._terminated.value = 1  # stop Trex clinet
276
277         self.connection.execute("fuser -n tcp %s %s -k > /dev/null 2>&1" %
278                                 (TREX_SYNC_PORT, TREX_ASYNC_PORT))
279
280         if self._traffic_process:
281             self._traffic_process.terminate()