standardize ssh auth
[yardstick.git] / yardstick / network_services / vnf_generic / vnf / tg_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 acts as traffic generation and vnf definitions based on IETS Spec """
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 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
31
32 LOG = logging.getLogger(__name__)
33 DURATION = 30
34 WAIT_QUEUE = 1
35 TREX_SYNC_PORT = 4500
36 TREX_ASYNC_PORT = 4501
37
38
39 class TrexTrafficGen(GenericTrafficGen):
40     """
41     This class handles mapping traffic profile and generating
42     traffic for given testcase
43     """
44
45     def __init__(self, vnfd):
46         super(TrexTrafficGen, self).__init__(vnfd)
47         self._result = {}
48         self._queue = multiprocessing.Queue()
49         self._terminated = multiprocessing.Value('i', 0)
50         self._traffic_process = None
51         self._vpci_ascending = None
52         self.client = None
53         self.my_ports = None
54         self.client_started = multiprocessing.Value('i', 0)
55
56         mgmt_interface = vnfd["mgmt-interface"]
57
58         self.connection = ssh.SSH.from_node(mgmt_interface)
59         self.connection.wait()
60
61     @classmethod
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)
66         return octets
67
68     def _generate_trex_cfg(self, vnfd):
69         """
70
71         :param vnfd: vnfd.yaml
72         :return: trex_cfg.yaml file
73         """
74         trex_cfg = dict(
75             port_limit=0,
76             version='2',
77             interfaces=[],
78             port_info=list(dict(
79             ))
80         )
81         trex_cfg["port_limit"] = len(vnfd["vdu"][0]["external-interface"])
82         trex_cfg["version"] = '2'
83
84         cfg_file = []
85         vpci = []
86         port = {}
87
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"])
92
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"])
97
98             trex_cfg["port_info"].append(port.copy())
99
100         trex_cfg["interfaces"] = vpci
101         cfg_file.append(trex_cfg)
102
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')
106
107         self._vpci_ascending = sorted(vpci)
108
109     @classmethod
110     def __setup_hugepages(cls, connection):
111         hugepages = \
112             connection.execute(
113                 "awk '/Hugepagesize/ { print $2$3 }' < /proc/meminfo")[1]
114         hugepages = hugepages.rstrip()
115
116         memory_path = \
117             '/sys/kernel/mm/hugepages/hugepages-%s/nr_hugepages' % hugepages
118         connection.execute("awk -F: '{ print $1 }' < %s" % memory_path)
119
120         pages = 16384 if hugepages.rstrip() == "2048kB" else 16
121         connection.execute("echo %s > %s" % (pages, memory_path))
122
123     def setup_vnf_environment(self, connection):
124         ''' setup dpdk environment needed for vnf to run '''
125
126         self.__setup_hugepages(connection)
127         connection.execute("modprobe uio && modprobe igb_uio")
128
129         exit_status = connection.execute("lsmod | grep -i igb_uio")[0]
130         if exit_status == 0:
131             return
132
133         dpdk = os.path.join(self.bin_path, "dpdk-16.07")
134         dpdk_setup = \
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]
138         if status:
139             connection.execute("bash %s dpdk >/dev/null 2>&1" % dpdk_setup)
140
141     def scale(self, flavor=""):
142         ''' scale vnfbased on flavor input '''
143         super(TrexTrafficGen, self).scale(flavor)
144
145     def instantiate(self, scenario_cfg, context_cfg):
146         self._generate_trex_cfg(self.vnfd)
147         self.setup_vnf_environment(self.connection)
148
149         trex = os.path.join(self.bin_path, "trex")
150         err = \
151             self.connection.execute("ls {} >/dev/null 2>&1".format(trex))[0]
152         if err != 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)
158
159         LOG.info("Starting TRex server...")
160         _tg_process = \
161             multiprocessing.Process(target=self._start_server)
162         _tg_process.start()
163         while True:
164             if not _tg_process.is_alive():
165                 raise RuntimeError("Traffic Generator process died.")
166             LOG.info("Waiting for TG Server to start.. ")
167             time.sleep(1)
168             status = \
169                 self.connection.execute("lsof -i:%s" % TREX_SYNC_PORT)[0]
170             if status == 0:
171                 LOG.info("TG server is up and running.")
172                 return _tg_process.exitcode
173
174     def listen_traffic(self, traffic_profile):
175         pass
176
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"]
183
184     def run_traffic(self, traffic_profile):
185         self._traffic_process = \
186             multiprocessing.Process(target=self._traffic_runner,
187                                     args=(traffic_profile, self._queue,
188                                           self.client_started,
189                                           self._terminated))
190         self._traffic_process.start()
191         # Wait for traffic process to start
192         while self.client_started.value == 0:
193             time.sleep(1)
194
195         return self._traffic_process.is_alive()
196
197     def _start_server(self):
198         mgmt_interface = self.vnfd["mgmt-interface"]
199
200         _server = ssh.SSH.from_node(mgmt_interface)
201         _server.wait()
202
203         _server.execute("fuser -n tcp %s %s -k > /dev/null 2>&1" %
204                         (TREX_SYNC_PORT, TREX_ASYNC_PORT))
205
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"
209
210         _server.execute(trex_cmd)
211
212     def _connect_client(self, client=None):
213         if client is 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
218         for idx in range(6):
219             try:
220                 client.connect()
221                 break
222             except STLError:
223                 LOG.info("Unable to connect to Trex Server.. Attempt %s", idx)
224                 time.sleep(5)
225         return client
226
227     def _traffic_runner(self, traffic_profile, queue,
228                         client_started, terminated):
229         LOG.info("Starting TRex client...")
230
231         self.my_ports = [0, 1]
232         self.client = self._connect_client()
233         self.client.reset(ports=self.my_ports)
234
235         self.client.remove_all_streams(self.my_ports)  # remove all streams
236
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
242                 terminated.value = 1
243                 last_res = {}
244
245             samples = {}
246             for vpci_idx in range(len(self._vpci_ascending)):
247                 name = \
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, {})
251                 samples[name] = \
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)
259             queue.put(samples)
260
261         self.client.disconnect()
262         terminated.value = 0
263
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)
268         return self._result
269
270     def terminate(self):
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()