1#!/router/bin/python
2
3import outer_packages
4#from trex_stl_lib.trex_stl_hltapi import CTRexHltApi, CStreamsPerPort
5from trex_stl_lib.trex_stl_hltapi import *
6import traceback
7import sys, time
8from pprint import pprint
9import argparse
10
11def error(err = None):
12    if not err:
13        raise Exception('Unknown exception, look traceback')
14    if type(err) is str and not err.startswith('[ERR]'):
15        err = '[ERR] ' + err
16    print err
17    sys.exit(1)
18
19def check_res(res):
20    if res['status'] == 0:
21        error('Encountered error:\n%s' % res['log'])
22    return res
23
24def print_brief_stats(res):
25    title_str = ' '*3
26    tx_str = 'TX:'
27    rx_str = 'RX:'
28    for port_id, stat in res.iteritems():
29        if type(port_id) is not int:
30            continue
31        title_str += ' '*10 + 'Port%s' % port_id
32        tx_str    += '%15s' % res[port_id]['aggregate']['tx']['total_pkts']
33        rx_str    += '%15s' % res[port_id]['aggregate']['rx']['total_pkts']
34    print(title_str)
35    print(tx_str)
36    print(rx_str)
37
38def wait_with_progress(seconds):
39    for i in range(0, seconds):
40        time.sleep(1)
41        sys.stdout.write('.')
42        sys.stdout.flush()
43    print('')
44
45if __name__ == "__main__":
46    try:
47        parser = argparse.ArgumentParser(description='Example of using stateless TRex via HLT API.', formatter_class=argparse.RawTextHelpFormatter)
48        parser.add_argument('-v', dest = 'verbose', default = 0, help='Stateless API verbosity:\n0: No prints\n1: Commands and their status\n2: Same as 1 + ZMQ in&out')
49        parser.add_argument('--device', dest = 'device', default = 'localhost', help='Address of TRex server')
50        args = parser.parse_args()
51        hlt_client = CTRexHltApi(verbose = int(args.verbose))
52
53        print('Connecting to %s...' % args.device)
54        res = check_res(hlt_client.connect(device = args.device, port_list = [0, 1], username = 'danklei', break_locks = True, reset = True))
55        port_handle = res['port_handle']
56        print('Connected, got port handles %s' % port_handle)
57        ports_streams_dict = CStreamsPerPort()
58        print hlt_client.traffic_control(action = 'poll')
59
60        print hlt_client.traffic_config(mode = 'create', l2_encap = 'ethernet_ii_vlan', rate_pps = 1,
61                                        l3_protocol = 'ipv4',
62                                        #length_mode = 'imix', l3_length = 200,
63                                        ipv6_dst_mode = 'decrement', ipv6_dst_count = 300, ipv6_dst_addr = 'fe80:0:0:0:0:0:0:000f',
64                                        port_handle = port_handle, port_handle2 = port_handle[1],
65                                        #save_to_yaml = '/tmp/d1.yaml',
66                                        #stream_id = 1,
67                                        )
68        print hlt_client.traffic_control(action = 'poll')
69        print hlt_client.traffic_control(action = 'run')
70        print hlt_client.traffic_control(action = 'poll')
71        wait_with_progress(2)
72        print hlt_client.traffic_control(action = 'poll')
73        print hlt_client.traffic_control(action = 'stop')
74        print hlt_client.traffic_control(action = 'poll')
75        print hlt_client.traffic_stats(mode = 'aggregate')
76        print hlt_client.traffic_control(action = 'clear_stats')
77        wait_with_progress(1)
78        print hlt_client.traffic_stats(mode = 'aggregate')
79
80        wait_with_progress(1)
81        print hlt_client.traffic_stats(mode = 'aggregate')
82        wait_with_progress(1)
83        print hlt_client.traffic_stats(mode = 'aggregate')
84        wait_with_progress(1)
85        print hlt_client.traffic_stats(mode = 'aggregate')
86        #print res
87        #print hlt_client._streams_history
88        #print hlt_client.trex_client._STLClient__get_all_streams(port_id = port_handle[0])
89        #print hlt_client.trex_client._STLClient__get_all_streams(port_id = port_handle[1])
90        #ports_streams_dict.add_streams_from_res(res)
91        sys.exit(0)
92        res = check_res(hlt_client.traffic_config(mode = 'create', l2_encap = 'ethernet_ii_vlan', rate_pps = 1,
93                                                  port_handle = port_handle[0], port_handle2 = port_handle[1], save_to_yaml = '/tmp/d1.yaml',
94                                                  l4_protocol = 'udp',
95                                                  #udp_src_port_mode = 'decrement',
96                                                  #udp_src_port_count = 10, udp_src_port = 5,
97                                                  ))
98        ports_streams_dict.add_streams_from_res(res)
99        sys.exit(0)
100        #print ports_streams_dict
101        #print hlt_client.trex_client._STLClient__get_all_streams(port_id = port_handle[0])
102        res = check_res(hlt_client.traffic_config(mode = 'modify', port_handle = port_handle[0], stream_id = ports_streams_dict[0][0],
103                                                  mac_src = '1-2-3:4:5:6', l4_protocol = 'udp', save_to_yaml = '/tmp/d2.yaml'))
104        #print hlt_client.trex_client._STLClient__get_all_streams(port_id = port_handle[0])
105        #print hlt_client._streams_history
106        res = check_res(hlt_client.traffic_config(mode = 'modify', port_handle = port_handle[0], stream_id = ports_streams_dict[0][0],
107                                                  mac_dst = '{ 7 7 7-7:7:7}', save_to_yaml = '/tmp/d3.yaml'))
108        #print hlt_client.trex_client._STLClient__get_all_streams(port_id = port_handle[0])
109        check_res(hlt_client.traffic_config(mode = 'reset', port_handle = port_handle))
110
111        res = check_res(hlt_client.traffic_config(mode = 'create', bidirectional = True, length_mode = 'fixed',
112                                                  port_handle = port_handle[0], port_handle2 = port_handle[1],
113                                                  transmit_mode = 'single_burst', pkts_per_burst = 100, rate_pps = 100,
114                                                  mac_src = '1-2-3-4-5-6',
115                                                  mac_dst = '6:5:4:4:5:6',
116                                                  save_to_yaml = '/tmp/imix.yaml'))
117        ports_streams_dict.add_streams_from_res(res)
118
119        print('Create single_burst 100 packets rate_pps=100 on port 0')
120        res = check_res(hlt_client.traffic_config(mode = 'create', port_handle = port_handle[0], transmit_mode = 'single_burst',
121                                                  pkts_per_burst = 100, rate_pps = 100))
122        ports_streams_dict.add_streams_from_res(res)
123
124        # playground - creating various streams on port 1
125        res = check_res(hlt_client.traffic_config(mode = 'create', port_handle = port_handle[1], save_to_yaml = '/tmp/hlt2.yaml',
126                        tcp_src_port_mode = 'decrement',
127                        tcp_src_port_count = 10, tcp_dst_port_count = 10, tcp_dst_port_mode = 'random'))
128        ports_streams_dict.add_streams_from_res(res)
129
130        res = check_res(hlt_client.traffic_config(mode = 'create', port_handle = port_handle[1], save_to_yaml = '/tmp/hlt3.yaml',
131                        l4_protocol = 'udp',
132                        udp_src_port_mode = 'decrement',
133                        udp_src_port_count = 10, udp_dst_port_count = 10, udp_dst_port_mode = 'random'))
134        ports_streams_dict.add_streams_from_res(res)
135
136        res = check_res(hlt_client.traffic_config(mode = 'create', port_handle = port_handle[1], save_to_yaml = '/tmp/hlt4.yaml',
137                        length_mode = 'increment',
138                        #ip_src_addr = '192.168.1.1', ip_src_mode = 'increment', ip_src_count = 5,
139                        ip_dst_addr = '5.5.5.5', ip_dst_mode = 'random', ip_dst_count = 2))
140        ports_streams_dict.add_streams_from_res(res)
141
142        res = check_res(hlt_client.traffic_config(mode = 'create', port_handle = port_handle[1], save_to_yaml = '/tmp/hlt5.yaml',
143                        length_mode = 'decrement', frame_size_min = 100, frame_size_max = 3000,
144                        #ip_src_addr = '192.168.1.1', ip_src_mode = 'increment', ip_src_count = 5,
145                        #ip_dst_addr = '5.5.5.5', ip_dst_mode = 'random', ip_dst_count = 2
146                        ))
147        ports_streams_dict.add_streams_from_res(res)
148
149        # remove the playground
150        check_res(hlt_client.traffic_config(mode = 'reset', port_handle = port_handle[1]))
151
152        print('Create continuous stream for port 1, rate_pps = 1')
153        res = check_res(hlt_client.traffic_config(mode = 'create', port_handle = port_handle[1], save_to_yaml = '/tmp/hlt1.yaml',
154                        #length_mode = 'increment', l3_length_min = 200,
155                        ip_src_addr = '192.168.1.1', ip_src_mode = 'increment', ip_src_count = 5,
156                        ip_dst_addr = '5.5.5.5', ip_dst_mode = 'random', ip_dst_count = 2))
157
158        check_res(hlt_client.traffic_control(action = 'run', port_handle = port_handle))
159        wait_with_progress(1)
160        print('Sample after 1 seconds (only packets count)')
161        res = check_res(hlt_client.traffic_stats(mode = 'all', port_handle = port_handle))
162        print_brief_stats(res)
163        print ''
164
165        print('Port 0 has finished the burst, put continuous instead with rate 1000. No stopping of other ports.')
166        check_res(hlt_client.traffic_control(action = 'stop', port_handle = port_handle[0]))
167        check_res(hlt_client.traffic_config(mode = 'reset', port_handle = port_handle[0]))
168        res = check_res(hlt_client.traffic_config(mode = 'create', port_handle = port_handle[0], rate_pps = 1000))
169        ports_streams_dict.add_streams_from_res(res)
170        check_res(hlt_client.traffic_control(action = 'run', port_handle = port_handle[0]))
171        wait_with_progress(5)
172        print('Sample after another 5 seconds (only packets count)')
173        res = check_res(hlt_client.traffic_stats(mode = 'aggregate', port_handle = port_handle))
174        print_brief_stats(res)
175        print ''
176
177        print('Stop traffic at port 1')
178        res = check_res(hlt_client.traffic_control(action = 'stop', port_handle = port_handle[1]))
179        wait_with_progress(5)
180        print('Sample after another %s seconds (only packets count)' % 5)
181        res = check_res(hlt_client.traffic_stats(mode = 'aggregate', port_handle = port_handle))
182        print_brief_stats(res)
183        print ''
184        print('Full HLT stats:')
185        pprint(res)
186
187        check_res(hlt_client.cleanup_session())
188    except Exception as e:
189        print(traceback.print_exc())
190        print(e)
191        raise
192    finally:
193        print('Done.')
194