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 acts as traffic generation and vnf definitions based on IETS Spec """
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 yardstick.network_services.utils import provision_tool
28 from stl.trex_stl_lib.trex_stl_client import STLClient
29 from stl.trex_stl_lib.trex_stl_client import LoggerApi
30 from stl.trex_stl_lib.trex_stl_exceptions import STLError
32 LOG = logging.getLogger(__name__)
36 TREX_ASYNC_PORT = 4501
39 class TrexTrafficGen(GenericTrafficGen):
41 This class handles mapping traffic profile and generating
42 traffic for given testcase
45 def __init__(self, vnfd):
46 super(TrexTrafficGen, self).__init__(vnfd)
48 self._queue = multiprocessing.Queue()
49 self._terminated = multiprocessing.Value('i', 0)
50 self._traffic_process = None
51 self._vpci_ascending = None
54 self.client_started = multiprocessing.Value('i', 0)
56 mgmt_interface = vnfd["mgmt-interface"]
58 self.connection = ssh.SSH.from_node(mgmt_interface)
59 self.connection.wait()
62 def _split_mac_address_into_list(cls, mac):
63 octets = mac.split(':')
64 for i, elem in enumerate(octets):
65 octets[i] = "0x" + str(elem)
68 def _generate_trex_cfg(self, vnfd):
71 :param vnfd: vnfd.yaml
72 :return: trex_cfg.yaml file
81 trex_cfg["port_limit"] = len(vnfd["vdu"][0]["external-interface"])
82 trex_cfg["version"] = '2'
88 for interface in range(len(vnfd["vdu"][0]["external-interface"])):
89 ext_intrf = vnfd["vdu"][0]["external-interface"]
90 virtual_interface = ext_intrf[interface]["virtual-interface"]
91 vpci.append(virtual_interface["vpci"])
93 port["src_mac"] = self._split_mac_address_into_list(
94 virtual_interface["local_mac"])
95 port["dest_mac"] = self._split_mac_address_into_list(
96 virtual_interface["dst_mac"])
98 trex_cfg["port_info"].append(port.copy())
100 trex_cfg["interfaces"] = vpci
101 cfg_file.append(trex_cfg)
103 with open('/tmp/trex_cfg.yaml', 'w') as outfile:
104 outfile.write(yaml.safe_dump(cfg_file, default_flow_style=False))
105 self.connection.put('/tmp/trex_cfg.yaml', '/etc')
107 self._vpci_ascending = sorted(vpci)
110 def __setup_hugepages(cls, connection):
113 "awk '/Hugepagesize/ { print $2$3 }' < /proc/meminfo")[1]
114 hugepages = hugepages.rstrip()
117 '/sys/kernel/mm/hugepages/hugepages-%s/nr_hugepages' % hugepages
118 connection.execute("awk -F: '{ print $1 }' < %s" % memory_path)
120 pages = 16384 if hugepages.rstrip() == "2048kB" else 16
121 connection.execute("echo %s > %s" % (pages, memory_path))
123 def setup_vnf_environment(self, connection):
124 ''' setup dpdk environment needed for vnf to run '''
126 self.__setup_hugepages(connection)
127 connection.execute("modprobe uio && modprobe igb_uio")
129 exit_status = connection.execute("lsmod | grep -i igb_uio")[0]
133 dpdk = os.path.join(self.bin_path, "dpdk-16.07")
135 provision_tool(self.connection,
136 os.path.join(self.bin_path, "nsb_setup.sh"))
137 status = connection.execute("ls {} >/dev/null 2>&1".format(dpdk))[0]
139 connection.execute("bash %s dpdk >/dev/null 2>&1" % dpdk_setup)
141 def scale(self, flavor=""):
142 ''' scale vnfbased on flavor input '''
143 super(TrexTrafficGen, self).scale(flavor)
145 def instantiate(self, scenario_cfg, context_cfg):
146 self._generate_trex_cfg(self.vnfd)
147 self.setup_vnf_environment(self.connection)
149 trex = os.path.join(self.bin_path, "trex")
151 self.connection.execute("ls {} >/dev/null 2>&1".format(trex))[0]
153 LOG.info("Copying trex to destination...")
154 self.connection.put("/root/.bash_profile", "/root/.bash_profile")
155 self.connection.put(trex, trex, True)
156 ko_src = os.path.join(trex, "scripts/ko/src/")
157 self.connection.execute("cd %s && make && make install" % ko_src)
159 LOG.info("Starting TRex server...")
161 multiprocessing.Process(target=self._start_server)
164 if not _tg_process.is_alive():
165 raise RuntimeError("Traffic Generator process died.")
166 LOG.info("Waiting for TG Server to start.. ")
169 self.connection.execute("lsof -i:%s" % TREX_SYNC_PORT)[0]
171 LOG.info("TG server is up and running.")
172 return _tg_process.exitcode
174 def listen_traffic(self, traffic_profile):
177 def _get_logical_if_name(self, vpci):
178 ext_intf = self.vnfd["vdu"][0]["external-interface"]
179 for interface in range(len(self.vnfd["vdu"][0]["external-interface"])):
180 virtual_intf = ext_intf[interface]["virtual-interface"]
181 if virtual_intf["vpci"] == vpci:
182 return ext_intf[interface]["name"]
184 def run_traffic(self, traffic_profile):
185 self._traffic_process = \
186 multiprocessing.Process(target=self._traffic_runner,
187 args=(traffic_profile, self._queue,
190 self._traffic_process.start()
191 # Wait for traffic process to start
192 while self.client_started.value == 0:
195 return self._traffic_process.is_alive()
197 def _start_server(self):
198 mgmt_interface = self.vnfd["mgmt-interface"]
200 _server = ssh.SSH.from_node(mgmt_interface)
203 _server.execute("fuser -n tcp %s %s -k > /dev/null 2>&1" %
204 (TREX_SYNC_PORT, TREX_ASYNC_PORT))
206 trex_path = os.path.join(self.bin_path, "trex/scripts")
207 path = get_nsb_option("trex_path", trex_path)
208 trex_cmd = "cd " + path + "; sudo ./t-rex-64 -i > /dev/null 2>&1"
210 _server.execute(trex_cmd)
212 def _connect_client(self, client=None):
214 client = STLClient(username=self.vnfd["mgmt-interface"]["user"],
215 server=self.vnfd["mgmt-interface"]["ip"],
216 verbose_level=LoggerApi.VERBOSE_QUIET)
217 # try to connect with 5s intervals, 30s max
223 LOG.info("Unable to connect to Trex Server.. Attempt %s", idx)
227 def _traffic_runner(self, traffic_profile, queue,
228 client_started, terminated):
229 LOG.info("Starting TRex client...")
231 self.my_ports = [0, 1]
232 self.client = self._connect_client()
233 self.client.reset(ports=self.my_ports)
235 self.client.remove_all_streams(self.my_ports) # remove all streams
237 while not terminated.value:
238 traffic_profile.execute(self)
239 client_started.value = 1
240 last_res = self.client.get_stats(self.my_ports)
241 if not isinstance(last_res, dict): # added for mock unit test
246 for vpci_idx in range(len(self._vpci_ascending)):
248 self._get_logical_if_name(self._vpci_ascending[vpci_idx])
249 # fixme: VNFDs KPIs values needs to be mapped to TRex structure
250 xe_value = last_res.get(vpci_idx, {})
252 {"rx_throughput_fps": float(xe_value.get("rx_pps", 0.0)),
253 "tx_throughput_fps": float(xe_value.get("tx_pps", 0.0)),
254 "rx_throughput_mbps": float(xe_value.get("rx_bps", 0.0)),
255 "tx_throughput_mbps": float(xe_value.get("tx_bps", 0.0)),
256 "in_packets": xe_value.get("ipackets", 0),
257 "out_packets": xe_value.get("opackets", 0)}
258 time.sleep(WAIT_QUEUE)
261 self.client.disconnect()
264 def collect_kpi(self):
265 if not self._queue.empty():
266 self._result.update(self._queue.get())
267 LOG.debug("trex collect Kpis %s", self._result)
271 self.connection.execute("fuser -n tcp %s %s -k > /dev/null 2>&1" %
272 (TREX_SYNC_PORT, TREX_ASYNC_PORT))
273 self.traffic_finished = True
274 if self._traffic_process:
275 self._traffic_process.terminate()