1 # Copyright (c) 2016-2017 Intel Corporation
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
7 # http://www.apache.org/licenses/LICENSE-2.0
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 """
16 from __future__ import absolute_import
17 from __future__ import print_function
18 import multiprocessing
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
31 LOGGING = logging.getLogger(__name__)
36 TREX_ASYNC_PORT = 4501
39 class TrexTrafficGenRFC(GenericTrafficGen):
41 This class handles mapping traffic profile and generating
42 traffic for rfc2544 testcase.
45 def __init__(self, vnfd):
46 super(TrexTrafficGenRFC, self).__init__(vnfd)
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
57 mgmt_interface = self.vnfd["mgmt-interface"]
59 self.connection = ssh.SSH.from_node(mgmt_interface)
60 self.connection.wait()
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)
69 def _generate_trex_cfg(self, vnfd):
72 :param vnfd: vnfd.yaml
73 :return: trex_cfg.yaml file
82 trex_cfg["port_limit"] = len(vnfd["vdu"][0]["external-interface"])
83 trex_cfg["version"] = '2'
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"])
95 self._split_mac_address_into_list(virt_intf["local_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())
103 trex_cfg["interfaces"] = vpci
104 cfg_file.append(trex_cfg)
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')
110 self._vpci_ascending = sorted(vpci)
112 def scale(self, flavor=""):
113 ''' scale vnfbased on flavor input '''
114 super(TrexTrafficGenRFC, self).scale(flavor)
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")
121 self.connection.execute("ls {} >/dev/null 2>&1".format(trex))
123 self.connection.put(trex, trex, True)
125 LOGGING.debug("Starting TRex server...")
127 multiprocessing.Process(target=self._start_server)
130 LOGGING.info("Waiting for TG Server to start.. ")
131 time.sleep(WAIT_TIME)
134 self.connection.execute("lsof -i:%s" % TREX_SYNC_PORT)[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.")
141 def listen_traffic(self, traffic_profile):
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"]
151 def run_traffic(self, traffic_profile,
152 client_started=multiprocessing.Value('i', 0)):
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:
163 return self._traffic_process.is_alive()
165 def _start_server(self):
166 mgmt_interface = self.vnfd["mgmt-interface"]
168 _server = ssh.SSH.from_node(mgmt_interface)
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")
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"
179 _server.execute(trex_cmd)
181 def _connect_client(self, client=None):
183 client = STLClient(username=self.vnfd["mgmt-interface"]["user"],
184 server=self.vnfd["mgmt-interface"]["ip"],
185 verbose_level=LoggerApi.VERBOSE_QUIET)
191 LOGGING.info("Unable to connect to Trex. Attempt %s", idx)
192 time.sleep(WAIT_TIME)
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:
202 tc_options['rfc2544'].get('allowed_drop_rate', '0.8 - 1.0')
204 tolerance = tolerance.split('-')
205 min_tol = float(tolerance[0])
206 if len(tolerance) == 2:
207 max_tol = float(tolerance[1])
209 max_tol = float(tolerance[0])
211 return [min_tol, max_tol]
213 def _traffic_runner(self, traffic_profile, queue,
214 client_started, terminated):
215 LOGGING.info("Starting TRex client...")
218 with open(self.tc_file_name) as tc_file:
219 tc_yaml = yaml.load(tc_file.read())
221 tolerance = self._get_rfc_tolerance(tc_yaml)
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
233 self.client.stop(self.my_ports)
234 time.sleep(WAIT_TIME)
235 last_res = self.client.get_stats(self.my_ports)
237 for vpci_idx in range(len(self._vpci_ascending)):
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):
246 {"rx_throughput_fps":
247 float(last_res.get(vpci_idx, {}).get("rx_pps", 0.0)),
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)),
255 last_res.get(vpci_idx, {}).get("ipackets", 0),
257 last_res.get(vpci_idx, {}).get("opackets", 0)}
260 traffic_profile.get_drop_percentage(self, samples,
261 tolerance[0], tolerance[1])
263 self.client.stop(self.my_ports)
264 self.client.disconnect()
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)
275 self._terminated.value = 1 # stop Trex clinet
277 self.connection.execute("fuser -n tcp %s %s -k > /dev/null 2>&1" %
278 (TREX_SYNC_PORT, TREX_ASYNC_PORT))
280 if self._traffic_process:
281 self._traffic_process.terminate()