3 # Copyright (c) 2016 Cisco and/or its affiliates.
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at:
8 # http://www.apache.org/licenses/LICENSE-2.0
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
16 """This script uses T-REX stateless API to drive t-rex instance.
19 - T-REX: https://github.com/cisco-system-traffic-generator/trex-core
20 - compiled and running T-REX process (eg. ./t-rex-64 -i -c 4)
21 - trex_stl_lib.api library
22 - Script must be executed on a node with T-REX instance
23 - 2 interfaces must be configured in configuretion file /etc/trex_cfg.yaml
25 ##################### Example of /etc/trex_cfg.yaml ##########################
26 - port_limit : 2 # numbers of ports to use
28 interfaces : ["84:00.0","84:00.1"] # PCI address of interfaces
29 port_info : # set eth mac addr
30 - dest_mac : [0x90,0xe2,0xba,0x1f,0x97,0xd5] # port 0
31 src_mac : [0x90,0xe2,0xba,0x1f,0x97,0xd4]
32 - dest_mac : [0x90,0xe2,0xba,0x1f,0x97,0xd4] # port 1
33 src_mac : [0x90,0xe2,0xba,0x1f,0x97,0xd5]
34 ##############################################################################
37 1. Configure traffic on running T-REX instance
38 2. Clear statistics on all ports
39 3. Ctart traffic with specified duration
40 4. Print statistics to stdout
51 sys.path.insert(0, "/opt/trex-core-2.06/scripts/automation/"+\
52 "trex_control_plane/stl/")
53 from trex_stl_lib.api import *
55 stream_table = {'IMIX_v4_1': [{'size': 64, 'pps': 28, 'isg':0},
56 {'size': 570, 'pps': 16, 'isg':0.1},
57 {'size': 1518, 'pps': 4, 'isg':0.2}]
60 def generate_payload(length):
63 :param length: Length of payload.
65 :return: Payload filled with chars.
70 alphabet_size = len(string.letters)
71 for i in range(length):
72 word += string.letters[(i % alphabet_size)]
77 def get_start_end_ipv6(start_ip, end_ip):
78 """Get start and end host from IPv6 as integer.
80 :param start_ip: Start IPv6.
81 :param end_ip: End IPv6.
82 :type start_ip: string
84 :return: Start host, end host.
89 ip1 = socket.inet_pton(socket.AF_INET6, start_ip)
90 ip2 = socket.inet_pton(socket.AF_INET6, end_ip)
92 hi1, lo1 = struct.unpack('!QQ', ip1)
93 hi2, lo2 = struct.unpack('!QQ', ip2)
95 if ((hi1 << 64) | lo1) > ((hi2 << 64) | lo2):
96 print "IPv6: start_ip is greater then end_ip"
99 max_p1 = abs(int(lo1) - int(lo2)) + 1
101 except AddressValueError as ex_error:
105 return base_p1, max_p1
107 def create_streams_v46(base_pkt_a, base_pkt_b, vm1, vm2, frame_size):
108 """Create STLStream streams
110 :param base_pkt_a: Base packet a for stream_a
111 :param base_pkt_b: Base packet b for stream_b
112 :param vm1: vm for stream_a
113 :param vm2: vm for stream_b
114 :param frame_size: frame size or name of traffic profile
115 :type base_pkt_a: Eth (scapy)
116 :type base_pkt_b: Eth (scapy)
117 :type vm1: STLScVmRaw
118 :type vm2: STLScVmRaw
119 :frame_size: int or string
120 :return: stream_a, stream_b, stream_a_latency, stream_b_latency
121 :rtype: STLStream, STLStream, STLStream, STLStream
124 if type(frame_size) is int:
126 fsize_no_fcs = frame_size - 4 # no FCS
127 pkt_a = STLPktBuilder(pkt=base_pkt_a/generate_payload(
128 max(0, fsize_no_fcs-len(base_pkt_a))), vm=vm1)
129 pkt_b = STLPktBuilder(pkt=base_pkt_b/generate_payload(
130 max(0, fsize_no_fcs-len(base_pkt_b))), vm=vm2)
131 pkt_lat_a = STLPktBuilder(pkt=base_pkt_a/generate_payload(
132 max(0, fsize_no_fcs-len(base_pkt_a))))
133 pkt_lat_b = STLPktBuilder(pkt=base_pkt_b/generate_payload(
134 max(0, fsize_no_fcs-len(base_pkt_b))))
135 lat_stream1 = STLStream(packet=pkt_lat_a,
136 flow_stats=STLFlowLatencyStats(pg_id=0),
137 mode=STLTXCont(pps=1000))
138 # second traffic stream with a phase of 10ns (inter stream gap)
139 lat_stream2 = STLStream(packet=pkt_lat_b,
141 flow_stats=STLFlowLatencyStats(pg_id=1),
142 mode=STLTXCont(pps=1000))
144 stream1 = STLStream(packet=pkt_a,
145 mode=STLTXCont(pps=1000))
146 # second traffic stream with a phase of 10ns (inter stream gap)
147 stream2 = STLStream(packet=pkt_b,
149 mode=STLTXCont(pps=1000))
150 elif type(frame_size) is str:
156 for x in stream_table[frame_size]:
157 fsize_no_fcs = x['size'] - 4 # no FCS
158 pkt_a = STLPktBuilder(pkt=base_pkt_a/generate_payload(
159 max(0, fsize_no_fcs-len(base_pkt_a))), vm=vm1)
160 pkt_b = STLPktBuilder(pkt=base_pkt_b/generate_payload(
161 max(0, fsize_no_fcs-len(base_pkt_b))), vm=vm2)
163 stream1.append(STLStream(packet=pkt_a,
165 mode=STLTXCont(pps=x['pps'])))
166 stream2.append(STLStream(packet=pkt_b,
168 mode=STLTXCont(pps=x['pps'])))
171 raise ValueError("Unknown frame_size type")
173 return (stream1, stream2, lat_stream1, lat_stream2)
175 def create_streams(traffic_options, frame_size=64):
176 """Create two IP packets to be used in stream.
178 :param traffic_options: Parameters for packets.
179 :param frame_size: Size of L2 frame.
180 :type traffic_options: list
181 :type frame_size: int
182 :return: Packet instances.
183 :rtype: Tuple of STLPktBuilder
186 if type(frame_size) is int and frame_size < 64:
187 print_error("Frame min. size is 64B")
190 p1_src_start_ip = traffic_options['p1_src_start_ip']
191 p1_src_end_ip = traffic_options['p1_src_end_ip']
192 p1_dst_start_ip = traffic_options['p1_dst_start_ip']
193 p2_src_start_ip = traffic_options['p2_src_start_ip']
194 p2_src_end_ip = traffic_options['p2_src_end_ip']
195 p2_dst_start_ip = traffic_options['p2_dst_start_ip']
197 p1_dst_end_ip = traffic_options['p1_dst_end_ip']
198 p2_dst_end_ip = traffic_options['p2_dst_end_ip']
200 base_pkt_a = Ether()/IP(src=p1_src_start_ip, dst=p1_dst_start_ip, proto=61)
201 base_pkt_b = Ether()/IP(src=p2_src_start_ip, dst=p2_dst_start_ip, proto=61)
203 # The following code applies raw instructions to packet (IP src/dst
204 # increment). It splits the generated traffic by "ip_src"/"ip_dst" variable
205 # to cores and fix IPv4 header checksum.
206 if p1_dst_end_ip and p2_dst_end_ip:
207 vm1 = STLScVmRaw([STLVmFlowVar(name="dst",
208 min_value=p1_dst_start_ip,
209 max_value=p1_dst_end_ip,
211 STLVmWrFlowVar(fv_name="dst", pkt_offset="IP.dst"),
212 STLVmFixIpv4(offset="IP"),
213 ], split_by_field="dst")
214 vm2 = STLScVmRaw([STLVmFlowVar(name="dst",
215 min_value=p2_dst_start_ip,
216 max_value=p2_dst_end_ip,
218 STLVmWrFlowVar(fv_name="dst", pkt_offset="IP.dst"),
219 STLVmFixIpv4(offset="IP"),
220 ], split_by_field="dst")
222 vm1 = STLScVmRaw([STLVmFlowVar(name="src",
223 min_value=p1_src_start_ip,
224 max_value=p1_src_end_ip,
226 STLVmWrFlowVar(fv_name="src", pkt_offset="IP.src"),
227 STLVmFixIpv4(offset="IP"),
228 ], split_by_field="src")
229 vm2 = STLScVmRaw([STLVmFlowVar(name="src",
230 min_value=p2_src_start_ip,
231 max_value=p2_src_end_ip,
233 STLVmWrFlowVar(fv_name="src", pkt_offset="IP.src"),
234 STLVmFixIpv4(offset="IP"),
235 ], split_by_field="src")
237 return create_streams_v46(base_pkt_a, base_pkt_b, vm1, vm2, frame_size)
240 def create_streams_v6(traffic_options, frame_size=78):
241 """Create two IPv6 packets to be used in stream.
243 :param traffic_options: Parameters for packets.
244 :param frame_size: Size of L2 frame.
245 :type traffic_options: List
246 :type frame_size: int
247 :return: Packet instances.
248 :rtype: Tuple of STLPktBuilder
251 if type(frame_size) is int and frame_size < 78:
252 print_error("Frame min. size is 78B")
255 p1_src_start_ip = traffic_options['p1_src_start_ip']
256 p1_src_end_ip = traffic_options['p1_src_end_ip']
257 p1_dst_start_ip = traffic_options['p1_dst_start_ip']
258 p2_src_start_ip = traffic_options['p2_src_start_ip']
259 p2_src_end_ip = traffic_options['p2_src_end_ip']
260 p2_dst_start_ip = traffic_options['p2_dst_start_ip']
262 base_p1, max_p1 = get_start_end_ipv6(p1_src_start_ip, p1_src_end_ip)
263 base_p2, max_p2 = get_start_end_ipv6(p2_src_start_ip, p2_src_end_ip)
265 base_pkt_a = Ether()/IPv6(src=p1_src_start_ip, dst=p1_dst_start_ip)
266 base_pkt_b = Ether()/IPv6(src=p2_src_start_ip, dst=p2_dst_start_ip)
268 # The following code applies raw instructions to packet (IP src increment).
269 # It splits the generated traffic by "ip_src" variable to cores
270 vm1 = STLScVmRaw([STLVmFlowVar(name="ipv6_src",
272 max_value=max_p1+base_p1,
274 STLVmWrFlowVar(fv_name="ipv6_src", pkt_offset="IPv6.src",
277 , split_by_field="ipv6_src")
279 # The following code applies raw instructions to packet (IP src increment).
280 # It splits the generated traffic by "ip_src" variable to cores
281 vm2 = STLScVmRaw([STLVmFlowVar(name="ipv6_src",
283 max_value=max_p2+base_p2,
285 STLVmWrFlowVar(fv_name="ipv6_src", pkt_offset="IPv6.src",
288 , split_by_field="ipv6_src")
290 return create_streams_v46(base_pkt_a, base_pkt_b, vm1, vm2, frame_size)
292 def simple_burst(stream_a, stream_b, stream_lat_a, stream_lat_b, duration, rate,
293 warmup_time, async_start, latency):
294 """Run the traffic with specific parameters.
296 :param pkt_a: Base packet for stream 1.
297 :param pkt_b: Base packet for stream 2.
298 :param pkt_lat_a: Base packet for latency stream 1.
299 :param pkt_lat_b: Base packet for latency stream 2.
300 :param duration: Duration of traffic run in seconds (-1=infinite).
301 :param rate: Rate of traffic run [percentage, pps, bps].
302 :param warmup_time: Warm up duration.
303 :param async_start: Start the traffic and exit.
304 :param latency: With latency stats.
305 :type pkt_a: STLPktBuilder
306 :type pkt_b: STLPktBuilder
307 :type pkt_lat_a: STLPktBuilder
308 :type pkt_lat_b: STLPktBuilder
311 :type warmup_time: int
312 :type async_start: bool
328 # turn this off if too many logs
329 #client.set_verbose("high")
334 # prepare our ports (my machine has 0 <--> 1 with static route)
335 client.reset(ports=[0, 1])
337 client.add_streams(stream_a, ports=[0])
338 client.add_streams(stream_b, ports=[1])
341 client.add_streams(stream_lat_a, ports=[0])
342 client.add_streams(stream_lat_b, ports=[1])
346 # clear the stats before injecting
349 # choose rate and start traffic
350 client.start(ports=[0, 1], mult=rate, duration=warmup_time)
353 client.wait_on_traffic(ports=[0, 1], timeout=(warmup_time+30))
355 if client.get_warnings():
356 for warning in client.get_warnings():
359 # read the stats after the test
360 stats = client.get_stats()
362 print "#####warmup statistics#####"
363 print json.dumps(stats, indent=4,
364 separators=(',', ': '), sort_keys=True)
365 lost_a = stats[0]["opackets"] - stats[1]["ipackets"]
366 lost_b = stats[1]["opackets"] - stats[0]["ipackets"]
368 print "\npackets lost from 0 --> 1: {0} pkts".format(lost_a)
369 print "packets lost from 1 --> 0: {0} pkts".format(lost_b)
371 # clear the stats before injecting
376 # choose rate and start traffic
377 client.start(ports=[0, 1], mult=rate, duration=duration)
381 client.wait_on_traffic(ports=[0, 1], timeout=(duration+30))
383 if client.get_warnings():
384 for warning in client.get_warnings():
387 # read the stats after the test
388 stats = client.get_stats()
390 print "#####statistics#####"
391 print json.dumps(stats, indent=4,
392 separators=(',', ': '), sort_keys=True)
393 lost_a = stats[0]["opackets"] - stats[1]["ipackets"]
394 lost_b = stats[1]["opackets"] - stats[0]["ipackets"]
398 str(stats["latency"][0]["latency"]["total_min"]),\
399 str(stats["latency"][0]["latency"]["average"]),\
400 str(stats["latency"][0]["latency"]["total_max"])))
402 str(stats["latency"][1]["latency"]["total_min"]),\
403 str(stats["latency"][1]["latency"]["average"]),\
404 str(stats["latency"][1]["latency"]["total_max"])))
406 total_sent = stats[0]["opackets"] + stats[1]["opackets"]
407 total_rcvd = stats[0]["ipackets"] + stats[1]["ipackets"]
409 print "\npackets lost from 0 --> 1: {0} pkts".format(lost_a)
410 print "packets lost from 1 --> 0: {0} pkts".format(lost_b)
412 except STLError as ex_error:
413 print_error(str(ex_error))
418 client.disconnect(stop_traffic=False, release_ports=True)
421 print "rate={0}, totalReceived={1}, totalSent={2}, "\
422 "frameLoss={3}, latencyStream0(usec)={4}, "\
423 "latencyStream1(usec)={5}".format(rate, total_rcvd,\
424 total_sent, lost_a+lost_b, lat_a, lat_b)
427 def print_error(msg):
428 """Print error message on stderr.
430 :param msg: Error message to print.
435 sys.stderr.write(msg+'\n')
439 """Parse arguments from cmd line.
441 :return: Parsed arguments.
442 :rtype ArgumentParser
445 parser = argparse.ArgumentParser()
446 parser.add_argument("-d", "--duration", required=True, type=int,
447 help="Duration of traffic run")
448 parser.add_argument("-s", "--frame_size", required=True,
449 help="Size of a Frame without padding and IPG")
450 parser.add_argument("-r", "--rate", required=True,
451 help="Traffic rate with included units (%, pps)")
452 parser.add_argument("-6", "--use_IPv6", action="store_true",
454 help="Use IPv6 traffic profile instead of IPv4")
455 parser.add_argument("--async", action="store_true",
457 help="Non-blocking call of the script")
458 parser.add_argument("--latency", action="store_true",
460 help="Add latency stream")
461 parser.add_argument("-w", "--warmup_time", type=int,
463 help="Traffic warmup time in seconds, 0 = disable")
464 # parser.add_argument("--p1_src_mac",
465 # help="Port 1 source MAC address")
466 # parser.add_argument("--p1_dst_mac",
467 # help="Port 1 destination MAC address")
468 parser.add_argument("--p1_src_start_ip", required=True,
469 help="Port 1 source start IP address")
470 parser.add_argument("--p1_src_end_ip",
472 help="Port 1 source end IP address")
473 parser.add_argument("--p1_dst_start_ip", required=True,
474 help="Port 1 destination start IP address")
475 parser.add_argument("--p1_dst_end_ip",
477 help="Port 1 destination end IP address")
478 # parser.add_argument("--p2_src_mac",
479 # help="Port 2 source MAC address")
480 # parser.add_argument("--p2_dst_mac",
481 # help="Port 2 destination MAC address")
482 parser.add_argument("--p2_src_start_ip", required=True,
483 help="Port 2 source start IP address")
484 parser.add_argument("--p2_src_end_ip",
486 help="Port 2 source end IP address")
487 parser.add_argument("--p2_dst_start_ip", required=True,
488 help="Port 2 destination start IP address")
489 parser.add_argument("--p2_dst_end_ip",
491 help="Port 2 destination end IP address")
493 return parser.parse_args()
501 _duration = args.duration
502 _latency = args.latency
503 if args.frame_size.isdigit():
504 _frame_size = int(args.frame_size)
506 _frame_size = args.frame_size
509 _use_ipv6 = args.use_IPv6
510 _async_call = args.async
511 _warmup_time = args.warmup_time
513 _traffic_options = {}
514 for attr in [a for a in dir(args) if a.startswith('p')]:
515 if getattr(args, attr) is not None:
516 _traffic_options[attr] = getattr(args, attr)
519 # WARNING: Trex limitation to IPv4 only. IPv6 is not yet supported.
520 print_error('IPv6 latency is not supported yet. Running without lat.')
523 stream_a, stream_b, stream_lat_a, stream_lat_b = create_streams_v6(
524 _traffic_options, frame_size=_frame_size)
526 stream_a, stream_b, stream_lat_a, stream_lat_b = create_streams(
527 _traffic_options, frame_size=_frame_size)
529 simple_burst(stream_a, stream_b, stream_lat_a, stream_lat_b,
530 _duration, _rate, _warmup_time, _async_call, _latency)
532 if __name__ == "__main__":