T-REX stl traffic send improvement for async calls
[csit.git] / resources / tools / t-rex / t-rex-stateless-stop.py
1 #!/usr/bin/python
2
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:
7 #
8 #     http://www.apache.org/licenses/LICENSE-2.0
9 #
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.
15
16 """This script uses T-REX stateless API to drive t-rex instance.
17
18 Requirements:
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
24 Functionality:
25 1. Stop any running traffic
26
27 """
28
29 import sys
30
31 sys.path.insert(0, "/opt/trex-core-2.00/scripts/automation/"+\
32                    "trex_control_plane/stl/")
33 from trex_stl_lib.api import *
34
35
36 def stop_all_traffic_streams():
37     """Stop traffic if any is running.
38
39     :return: nothing
40     """
41
42     # create client
43     client = STLClient()
44
45     try:
46         # turn this off if too many logs
47         #client.set_verbose("high")
48
49         # connect to server
50         client.connect()
51
52         client.acquire(force=True)
53         client.stop(ports=[0, 1])
54
55         # read the stats after the test
56         stats = client.get_stats()
57
58         print "#####statistics (approx.)#####"
59         print json.dumps(stats, indent=4,
60                          separators=(',', ': '), sort_keys=True)
61
62         lost_a = stats[0]["opackets"] - stats[1]["ipackets"]
63         lost_b = stats[1]["opackets"] - stats[0]["ipackets"]
64
65         total_sent = stats[0]["opackets"] + stats[1]["opackets"]
66         total_rcvd = stats[0]["ipackets"] + stats[1]["ipackets"]
67
68         print "\npackets lost from 0 --> 1:   {0} pkts".format(lost_a)
69         print "packets lost from 1 --> 0:   {0} pkts".format(lost_b)
70
71     except STLError as ex_error:
72         print_error(str(ex_error))
73         sys.exit(1)
74
75     finally:
76         client.disconnect()
77
78
79
80 def print_error(msg):
81     """Print error message on stderr.
82
83     :param msg: Error message to print.
84     :type msg: string
85     :return: nothing
86     """
87
88     sys.stderr.write(msg+'\n')
89
90
91 def main():
92     """Main function."""
93
94     stop_all_traffic_streams()
95
96 if __name__ == "__main__":
97     main()