Python3: TRex driver 01/20001/3
authorPeter Mikus <pmikus@cisco.com>
Thu, 6 Jun 2019 12:19:59 +0000 (12:19 +0000)
committerTibor Frank <tifrank@cisco.com>
Mon, 10 Jun 2019 07:53:37 +0000 (07:53 +0000)
Change-Id: I25f7598b52c87ec1a2d4c6f22680d5200b583e2c
Signed-off-by: Peter Mikus <pmikus@cisco.com>
resources/tools/trex/trex_server_info.py
resources/tools/trex/trex_stateless_profile.py
resources/tools/trex/trex_stateless_stop.py
resources/traffic_profiles/trex/profile_trex_stateless_base_class.py

index da49bfc..eaab6d7 100755 (executable)
@@ -1,4 +1,4 @@
-#!/usr/bin/python
+#!/usr/bin/python3
 
 # Copyright (c) 2019 Cisco and/or its affiliates.
 # Licensed under the Apache License, Version 2.0 (the "License");
 
 # Copyright (c) 2019 Cisco and/or its affiliates.
 # Licensed under the Apache License, Version 2.0 (the "License");
@@ -32,30 +32,21 @@ sys.path.insert(0, "/opt/trex-core-2.54/scripts/automation/"+\
                    "trex_control_plane/interactive/")
 from trex.stl.api import *
 
                    "trex_control_plane/interactive/")
 from trex.stl.api import *
 
-def get_server_system_info():
-    """Check server info and quit.
-
-    :return: nothing
-    """
-    # create client
+def main():
+    """Check server info and quit."""
     client = STLClient()
     client = STLClient()
-
     try:
         # connect to server
         client.connect()
     try:
         # connect to server
         client.connect()
+
         # get server info
         print(client.get_server_system_info())
     except STLError as ex_error:
         # get server info
         print(client.get_server_system_info())
     except STLError as ex_error:
-        sys.stderr.write(str(ex_error))
+        print(ex_error, file=sys.stderr)
         sys.exit(1)
     finally:
         client.disconnect()
 
 
         sys.exit(1)
     finally:
         client.disconnect()
 
 
-def main():
-    """Main function."""
-    get_server_system_info()
-
-
 if __name__ == "__main__":
     main()
 if __name__ == "__main__":
     main()
index e77c136..15e2157 100755 (executable)
@@ -1,4 +1,4 @@
-#!/usr/bin/python
+#!/usr/bin/python3
 
 # Copyright (c) 2019 Cisco and/or its affiliates.
 # Licensed under the Apache License, Version 2.0 (the "License");
 
 # Copyright (c) 2019 Cisco and/or its affiliates.
 # Licensed under the Apache License, Version 2.0 (the "License");
@@ -39,7 +39,6 @@ def fmt_latency(lat_min, lat_avg, lat_max):
     :return: Formatted and rounded output "min/avg/max"
     :rtype: string
     """
     :return: Formatted and rounded output "min/avg/max"
     :rtype: string
     """
-
     try:
         t_min = int(round(float(lat_min)))
     except ValueError:
     try:
         t_min = int(round(float(lat_min)))
     except ValueError:
@@ -96,7 +95,6 @@ def simple_burst(profile_file, duration, framesize, rate, warmup_time, port_0,
     :type async_start: bool
     :type unidirection: bool
     """
     :type async_start: bool
     :type unidirection: bool
     """
-
     client = None
     total_rcvd = 0
     total_sent = 0
     client = None
     total_rcvd = 0
     total_sent = 0
@@ -168,8 +166,7 @@ def simple_burst(profile_file, duration, framesize, rate, warmup_time, port_0,
             stats = client.get_stats()
 
             print("##### Warmup statistics #####")
             stats = client.get_stats()
 
             print("##### Warmup statistics #####")
-            print(json.dumps(stats, indent=4, separators=(',', ': '),
-                             sort_keys=True))
+            print(json.dumps(stats, indent=4, separators=(',', ': ')))
 
             lost_a = stats[port_0]["opackets"] - stats[port_1]["ipackets"]
             if not unidirection:
 
             lost_a = stats[port_0]["opackets"] - stats[port_1]["ipackets"]
             if not unidirection:
@@ -201,8 +198,7 @@ def simple_burst(profile_file, duration, framesize, rate, warmup_time, port_0,
             stats = client.get_stats()
 
             print("##### Statistics #####")
             stats = client.get_stats()
 
             print("##### Statistics #####")
-            print(json.dumps(stats, indent=4, separators=(',', ': '),
-                             sort_keys=True))
+            print(json.dumps(stats, indent=4, separators=(',', ': ')))
 
             lost_a = stats[port_0]["opackets"] - stats[port_1]["ipackets"]
             if not unidirection:
 
             lost_a = stats[port_0]["opackets"] - stats[port_1]["ipackets"]
             if not unidirection:
@@ -232,8 +228,8 @@ def simple_burst(profile_file, duration, framesize, rate, warmup_time, port_0,
                 print("packets lost from {p_1} --> {p_0}:   {v} pkts".format(
                 p_0=port_0, p_1=port_1, v=lost_b))
 
                 print("packets lost from {p_1} --> {p_0}:   {v} pkts".format(
                 p_0=port_0, p_1=port_1, v=lost_b))
 
-    except STLError as err:
-        sys.stderr.write("{0}\n".format(err))
+    except STLError as ex_error:
+        print(ex_error, file=sys.stderr)
         sys.exit(1)
 
     finally:
         sys.exit(1)
 
     finally:
@@ -243,10 +239,6 @@ def simple_burst(profile_file, duration, framesize, rate, warmup_time, port_0,
         else:
             if client:
                 client.disconnect()
         else:
             if client:
                 client.disconnect()
-            if isinstance(rate, unicode):
-                rate = rate.encode("utf-8")
-            if isinstance(duration, unicode):
-                duration = duration.encode("utf-8")
             print("rate={0!r}, totalReceived={1}, totalSent={2}, "
                   "frameLoss={3}, latencyStream0(usec)={4}, "
                   "latencyStream1(usec)={5}, targetDuration={d!r}".
             print("rate={0!r}, totalReceived={1}, totalSent={2}, "
                   "frameLoss={3}, latencyStream0(usec)={4}, "
                   "latencyStream1(usec)={5}, targetDuration={d!r}".
@@ -260,7 +252,6 @@ def main():
     It verifies the given command line arguments and runs "simple_burst"
     function.
     """
     It verifies the given command line arguments and runs "simple_burst"
     function.
     """
-
     parser = argparse.ArgumentParser()
     parser.add_argument("-p", "--profile",
                         required=True,
     parser = argparse.ArgumentParser()
     parser.add_argument("-p", "--profile",
                         required=True,
index 37988e7..9ded59a 100755 (executable)
@@ -1,4 +1,4 @@
-#!/usr/bin/python
+#!/usr/bin/python3
 
 # Copyright (c) 2019 Cisco and/or its affiliates.
 # Licensed under the Apache License, Version 2.0 (the "License");
 
 # Copyright (c) 2019 Cisco and/or its affiliates.
 # Licensed under the Apache License, Version 2.0 (the "License");
@@ -33,14 +33,9 @@ sys.path.insert(0, "/opt/trex-core-2.54/scripts/automation/"+\
 from trex.stl.api import *
 
 
 from trex.stl.api import *
 
 
-def stop_all_traffic_streams():
-    """Stop traffic if any is running.
-
-    :return: nothing
-    """
-    # create client
+def main():
+    """Stop traffic if any is running."""
     client = STLClient()
     client = STLClient()
-
     try:
         # connect to server
         client.connect()
     try:
         # connect to server
         client.connect()
@@ -52,8 +47,7 @@ def stop_all_traffic_streams():
         stats = client.get_stats()
 
         print("#####statistics (approx.)#####")
         stats = client.get_stats()
 
         print("#####statistics (approx.)#####")
-        print(json.dumps(stats, indent=4,
-                         separators=(',', ': '), sort_keys=True))
+        print(json.dumps(stats, indent=4, separators=(',', ': ')))
 
         lost_a = stats[0]["opackets"] - stats[1]["ipackets"]
         lost_b = stats[1]["opackets"] - stats[0]["ipackets"]
 
         lost_a = stats[0]["opackets"] - stats[1]["ipackets"]
         lost_b = stats[1]["opackets"] - stats[0]["ipackets"]
@@ -61,16 +55,10 @@ def stop_all_traffic_streams():
         print("\npackets lost from 0 --> 1:   {0} pkts".format(lost_a))
         print("packets lost from 1 --> 0:   {0} pkts".format(lost_b))
     except STLError as ex_error:
         print("\npackets lost from 0 --> 1:   {0} pkts".format(lost_a))
         print("packets lost from 1 --> 0:   {0} pkts".format(lost_b))
     except STLError as ex_error:
-        sys.stderr.write(str(ex_error))
+        print(ex_error, file=sys.stderr)
         sys.exit(1)
     finally:
         client.disconnect()
 
         sys.exit(1)
     finally:
         client.disconnect()
 
-
-def main():
-    """Main function."""
-    stop_all_traffic_streams()
-
-
 if __name__ == "__main__":
     main()
 if __name__ == "__main__":
     main()
index 1decc40..b5a4ba9 100755 (executable)
@@ -19,15 +19,13 @@ import socket
 import struct
 
 from random import choice
 import struct
 
 from random import choice
-from string import letters
+from string import ascii_letters
 
 from trex.stl.api import *
 
 
 class TrafficStreamsBaseClass(object):
 
 from trex.stl.api import *
 
 
 class TrafficStreamsBaseClass(object):
-    """Base class for stream profiles for T-rex traffic generator.
-    """
-
+    """Base class for stream profiles for T-rex traffic generator."""
     STREAM_TABLE = {
         'IMIX_v4': [
             {'size': 60, 'pps': 28, 'isg': 0},
     STREAM_TABLE = {
         'IMIX_v4': [
             {'size': 60, 'pps': 28, 'isg': 0},
@@ -42,7 +40,6 @@ class TrafficStreamsBaseClass(object):
     }
 
     def __init__(self):
     }
 
     def __init__(self):
-
         # Default value of frame size, it will be overwritten by the value of
         # "framesize" parameter of "get_streams" method.
         self.framesize = 64
         # Default value of frame size, it will be overwritten by the value of
         # "framesize" parameter of "get_streams" method.
         self.framesize = 64
@@ -59,10 +56,9 @@ class TrafficStreamsBaseClass(object):
         :returns: The generated payload.
         :rtype: str
         """
         :returns: The generated payload.
         :rtype: str
         """
-
         payload = ""
         for _ in range(length):
         payload = ""
         for _ in range(length):
-            payload += choice(letters)
+            payload += choice(ascii_letters)
 
         return payload
 
 
         return payload
 
@@ -78,7 +74,6 @@ class TrafficStreamsBaseClass(object):
         :raises: ValueError if start_ip is greater then end_ip.
         :raises: socket.error if the IP addresses are not valid IPv6 addresses.
         """
         :raises: ValueError if start_ip is greater then end_ip.
         :raises: socket.error if the IP addresses are not valid IPv6 addresses.
         """
-
         try:
             ip1 = socket.inet_pton(socket.AF_INET6, start_ip)
             ip2 = socket.inet_pton(socket.AF_INET6, end_ip)
         try:
             ip1 = socket.inet_pton(socket.AF_INET6, start_ip)
             ip2 = socket.inet_pton(socket.AF_INET6, end_ip)
@@ -117,7 +112,6 @@ class TrafficStreamsBaseClass(object):
         :returns: Traffic streams.
         :rtype: list
         """
         :returns: Traffic streams.
         :rtype: list
         """
-
         base_pkt_a, base_pkt_b, vm1, vm2 = self.define_packets()
 
         # In most cases you will not have to change the code below:
         base_pkt_a, base_pkt_b, vm1, vm2 = self.define_packets()
 
         # In most cases you will not have to change the code below:
@@ -204,7 +198,6 @@ class TrafficStreamsBaseClass(object):
         :returns: Traffic streams.
         :rtype: list
         """
         :returns: Traffic streams.
         :rtype: list
         """
-
         self.framesize = kwargs['framesize']
 
         return self.create_streams()
         self.framesize = kwargs['framesize']
 
         return self.create_streams()