Client Module¶
The TRex Client provides access to the TRex server.
Client and interfaces
Multiple users can interact with one TRex server. Each user “owns” a different set of interfaces. The protocol is JSON-RPC2 over ZMQ transport.
In addition to the Python API, a console-based API interface is also available.
Python-like example:
c.start(ports = [0, 1], mult = "5mpps", duration = 10)
c.start(ports = [0, 1], mult = "5mpps", duration = 10, core_mask = [0x1,0xe] )
c.start(ports = [0, 1], mult = "5mpps", duration = 10, core_mask = core_mask=STLClient.CORE_MASK_PIN )
Console-like example:
c.start_line (" -f stl/udp_1pkt_simple.py -m 10mpps --port 0 1 ")
Example 1 - Typical Python API:
c = STLClient(username = "itay",server = "10.0.0.10", verbose_level = "error")
try:
# connect to server
c.connect()
# prepare our ports (my machine has 0 <--> 1 with static route)
c.reset(ports = [0, 1])
# add both streams to ports
c.add_streams(s1, ports = [0])
# clear the stats before injecting
c.clear_stats()
c.start(ports = [0, 1], mult = "5mpps", duration = 10)
# block until done
c.wait_on_traffic(ports = [0, 1])
# check for any warnings
if c.get_warnings():
# handle warnings here
pass
finally:
c.disconnect()
Example 2 - Dynamic API
#multi profile per port could be run
def dynamic_profile (self):
port_list = [self.tx_port, self.rx_port]
profile_list = ["p1", "p2"]
stream_pg_id = 0
port = 0
try:
# start profiles 0.p1 0.p2 (two profiles on all ports)
for profile in profile_list:
stream_pg_id = stream_pg_id + 1
s1 = STLStream(name = 'latency',
packet = self.pkt,
mode = STLTXCont(percentage = self.percentage),
flow_stats = STLFlowLatencyStats(pg_id = stream_pg_id))
port_profile = str(port) + "." + str(profile) #e.g 0.p1
self.c.add_streams([s1], ports = port_profile)
self.c.start(ports = port_profile)
# stop all profiles on port 0 using 0.*
self.c.stop(ports = str(port)+".*")
except STLError as e:
assert False , '{0}'.format(e)
STLClient class¶
-
class
trex.stl.trex_stl_client.STLClient(username='hhaim', server='localhost', sync_port=4501, async_port=4500, verbose_level='error', logger=None, sync_timeout=None, async_timeout=None)[source]¶ TRex stateless client
Parameters: - username : string
the user name, for example imarom
- server : string
the server name or ip
- sync_port : int
the RPC port
- async_port : int
the ASYNC port (subscriber port)
- verbose_level: str
one of “none”, “critical”, “error”, “info”, “debug”
- logger: instance of AbstractLogger
if None, will use ScreenLogger
- sync_timeout: int
time in sec for timeout for RPC commands. for local lab keep it as default (3 sec) higher number would be more resilient for Firewalls but slower to identify real server crash
- async_timeout: int
time in sec for timeout for async notification. for local lab keep it as default (3 sec) higher number would be more resilient for Firewalls but slower to identify real server crash
-
reset(ports=None, restart=False)[source]¶ Force acquire ports, stop the traffic, remove all streams and clear stats
Parameters: - ports : list
Ports on which to execute the command
- restart: bool
Restart the NICs (link down / up)
Raises: TRexError
-
acquire(ports=None, force=False, sync_streams=True)[source]¶ Acquires ports for executing commands
Parameters: - ports : list
Ports on which to execute the command
- force : bool
Force acquire the ports.
- sync_streams: bool
sync with the server about the configured streams
Raises: TRexError
-
release(ports=None)[source]¶ Release ports
Parameters: - ports : list
Ports on which to execute the command
Raises: TRexError
-
set_service_mode(ports=None, enabled=True, filtered=False, mask=None)[source]¶ based on
trex.stl.trex_stl_client.STLClient.set_service_mode_base()
-
remove_all_streams(ports=None)[source]¶ remove all streams from port(s)
Parameters: - ports : list
Ports on which to execute the command
Raises: TRexError
-
add_streams(streams, ports=None)[source]¶ Add a list of streams to port(s)
Parameters: - ports : list
Ports on which to execute the command
- streams: list
Streams to attach (or profile)
Returns: List of stream IDs in order of the stream list
Raises: TRexError
-
add_profile(filename, ports=None, **kwargs)[source]¶ - Add streams from profile by its type. Supported types are:.py.yaml.pcap file that converted to profile automatically
Parameters: - filename : string
filename (with path) of the profile
- ports : list
list of ports to add the profile (default: all acquired)
- kwargs : dict
forward those key-value pairs to the profile (tunables)
Returns: List of stream IDs in order of the stream list
Raises: TRexError
-
remove_streams(stream_id_list, ports=None)[source]¶ Remove a list of streams from ports
Parameters: - stream_id_list: int or list of ints
Stream id list to remove
- ports : list
Ports on which to execute the command
Raises: TRexError
-
start(ports=None, mult='1', force=False, duration=-1, total=False, core_mask=None, synchronized=False)[source]¶ Start traffic on port(s)
Parameters: - ports : list
Ports on which to execute the command
- mult : str
Multiplier in a form of pps, bps, or line util in % Examples: “5kpps”, “10gbps”, “85%”, “32mbps”
- force : bool
If the ports are not in stopped mode or do not have sufficient bandwidth for the traffic, determines whether to stop the current traffic and force start. True: Force start False: Do not force start
- duration : int
Limit the run time (seconds) -1 = unlimited
- total : bool
Determines whether to divide the configured bandwidth among the ports, or to duplicate the bandwidth for each port. True: Divide bandwidth among the ports False: Duplicate
- core_mask: CORE_MASK_SPLIT, CORE_MASK_PIN, CORE_MASK_SINGLE or a list of masks (one per port)
Determine the allocation of cores per port In CORE_MASK_SPLIT all the traffic will be divided equally between all the cores associated with each port In CORE_MASK_PIN, for each dual ports (a group that shares the same cores) the cores will be divided half pinned for each port
- synchronized: bool
In case of several ports, ensure their transmitting time is syncronized. Must use adjacent ports (belong to same set of cores). Will set default core_mask to 0x1. Recommended ipg 1ms and more.
Raises: TRexError
-
stop(ports=None, rx_delay_ms=None)[source]¶ Stop port(s)
Parameters: - ports : list
Ports on which to execute the command
- rx_delay_ms : int
time to wait until RX filters are removed this value should reflect the time it takes packets which were transmitted to arrive to the destination. after this time the RX filters will be removed
Raises: TRexError
-
wait_on_traffic(ports=None, timeout=None, rx_delay_ms=None)[source]¶ Block until traffic on specified port(s) has ended
Parameters: - ports : list
Ports on which to execute the command
- timeout : int
timeout in seconds default will be blocking
- rx_delay_ms : int
Time to wait (in milliseconds) after last packet was sent, until RX filters used for measuring flow statistics and latency are removed. This value should reflect the time it takes packets which were transmitted to arrive to the destination. After this time, RX filters will be removed, and packets arriving for per flow statistics feature and latency flows will be counted as errors.
Raises: TRexTimeoutError- in case timeout has expired- :exe:’TRexError’
-
update(ports=None, mult='1', total=False, force=False)[source]¶ Update traffic on port(s)
Parameters: - ports : list
Ports on which to execute the command
- mult : str
Multiplier in a form of pps, bps, or line util in % Can also specify +/- Examples: “5kpps+”, “10gbps-”, “85%”, “32mbps”, “20%+”
- force : bool
If the ports are not in stopped mode or do not have sufficient bandwidth for the traffic, determines whether to stop the current traffic and force start. True: Force start False: Do not force start
- total : bool
Determines whether to divide the configured bandwidth among the ports, or to duplicate the bandwidth for each port. True: Divide bandwidth among the ports False: Duplicate
Raises: TRexError
-
update_streams(port, mult='1', force=False, stream_ids=None)[source]¶ - Temporary hack to update specific streams.Do not rely on this function, might be removed in future!Warning: Changing rates of specific streams causes out of sync between CP and DP regarding streams rate.In order to update rate of whole port, need to revert changes made to rates of those streams.
Parameters: - port : int
Port on which to execute the command
- mult : str
Multiplier in a form of pps, bps, or line util in % Examples: “5kpps”, “10gbps”, “85%”, “32mbps”
- force : bool
If the port are not in stopped mode or do not have sufficient bandwidth for the traffic, determines whether to stop the current traffic and force start. True: Force start False: Do not force start
Raises: TRexError
-
pause(ports=None)[source]¶ Pause traffic on port(s). Works only for ports that are active, and only if all streams are in Continuous mode.
Parameters: - ports : list
Ports on which to execute the command
Raises: TRexError
-
pause_streams(port, stream_ids)[source]¶ Temporary hack to pause specific streams. Does not change state of port. Do not rely on this function, might be removed in future!
Parameters: - port : int
Port on which to execute the command
- stream_ids : list
Stream IDs to pause
Raises: TRexError
-
resume(ports=None)[source]¶ Resume traffic on port(s)
Parameters: - ports : list
Ports on which to execute the command
Raises: TRexError
-
resume_streams(port, stream_ids)[source]¶ Temporary hack to resume specific streams. Does not change state of port. Do not rely on this function, might be removed in future!
Parameters: - port : int
Port on which to execute the command
- stream_ids : list
Stream IDs to resume
Raises: TRexError
-
push_remote(pcap_filename, ports=None, ipg_usec=None, speedup=1.0, count=1, duration=-1, is_dual=False, min_ipg_usec=None, force=False, src_mac_pcap=False, dst_mac_pcap=False)[source]¶ Push a remote server-reachable PCAP file the path must be fullpath accessible to the server
Parameters: - pcap_filename : str
PCAP file name in full path and accessible to the server
- ports : list
Ports on which to execute the command
- ipg_usec : float
Inter-packet gap in microseconds. Exclusive with min_ipg_usec
- speedup : float
A factor to adjust IPG. effectively IPG = IPG / speedup
- count: int
How many times to transmit the cap
- duration: float
Limit runtime by duration in seconds
- is_dual: bool
Inject from both directions. requires ERF file with meta data for direction. also requires that all the ports will be in master mode with their adjacent ports as slaves
- min_ipg_usec : float
Minimum inter-packet gap in microseconds to guard from too small ipg. Exclusive with ipg_usec
- force : bool
Ignore if port is active
- src_mac_pcap : bool
Source MAC address will be taken from pcap file if True.
- dst_mac_pcap : bool
Destination MAC address will be taken from pcap file if True.
Raises: TRexError
-
push_pcap(pcap_filename, ports=None, ipg_usec=None, speedup=1.0, count=1, duration=-1, force=False, vm=None, packet_hook=None, is_dual=False, min_ipg_usec=None, src_mac_pcap=False, dst_mac_pcap=False)[source]¶ Push a local PCAP to the server This is equivalent to loading a PCAP file to a profile and attaching the profile to port(s)
file size is limited to 1MB
Parameters: - pcap_filename : str
PCAP filename (accessible locally)
- ports : list
Ports on which to execute the command
- ipg_usec : float
Inter-packet gap in microseconds. Exclusive with min_ipg_usec
- speedup : float
A factor to adjust IPG. effectively IPG = IPG / speedup
- count: int
How many times to transmit the cap
- duration: float
Limit runtime by duration in seconds
- force: bool
Ignore file size limit - push any file size to the server also ignore if port is active
- vm: list of VM instructions
VM instructions to apply for every packet
- packet_hook : Callable or function
Will be applied to every packet
- is_dual: bool
Inject from both directions. Requires that all the ports will be in master mode with their adjacent ports as slaves
- min_ipg_usec : float
Minimum inter-packet gap in microseconds to guard from too small ipg. Exclusive with ipg_usec
- src_mac_pcap : bool
Source MAC address will be taken from pcap file if True.
- dst_mac_pcap : bool
Destination MAC address will be taken from pcap file if True.
Raises: TRexError
-
get_stats(ports=None, sync_now=True)[source]¶ Gets all statistics on given ports, flow stats and latency.
Parameters: ports: list
sync_now: boolean
-
clear_stats(ports=None, clear_global=True, clear_flow_stats=True, clear_latency_stats=True, clear_xstats=True)[source]¶ Clears statistics in given ports.
Parameters: ports: list
clear_global: boolean
clear_flow_stats: boolean
clear_latency_stats: boolean
clear_xstats: boolean
-
get_active_pgids()[source]¶ Get active packet group IDs
Parameters: None
Returns: Dict with entries ‘latency’ and ‘flow_stats’. Each entry contains list of used packet group IDs of the given type.
Raises: TRexError
-
get_pgid_stats(pgid_list=[])[source]¶ Get flow statistics for give list of pgids
Parameters: - pgid_list: list
pgids to get statistics on. If empty list, get statistics for all pgids. Allows to get statistics for 1024 flows in one call (will return error if asking for more).
Returns: Return dictionary containing packet group id statistics information gathered from the server.
key Meaning flow_stats Per flow statistics latency Per flow statistics regarding flow latency Below is description of each of the inner dictionaries.
flow_stats contains global dictionary, and dictionaries per packet group id (pg id). See structures below.
per pg_id flow stat dictionaries have following structure:
key Meaning rx_bps Received bits per second rate rx_bps_l1 Received bits per second rate, including layer one rx_bytes Total number of received bytes rx_pkts Total number of received packets rx_pps Received packets per second tx_bps Transmit bits per second rate tx_bps_l1 Transmit bits per second rate, including layer one tx_bytes Total number of sent bits tx_pkts Total number of sent packets tx_pps Transmit packets per second rate global flow stats dictionary has the following structure:
key Meaning rx_err Number of flow statistics packets received that we could not associate to any pg_id. This can happen if latency on the used setup is large. See wait_on_traffic rx_delay_ms parameter for details. tx_err Number of flow statistics packets transmitted that we could not associate to any pg_id. This is never expected. If you see this different than 0, please report. latency contains global dictionary, and dictionaries per packet group id (pg id). Each one with the following structure.
per pg_id latency stat dictionaries have following structure:
key Meaning err_cntrs Counters describing errors that occured with this pg id latency Information regarding packet latency Following are the inner dictionaries of latency
err-cntrs
key Meaning (see better explanation below the table) dropped How many packets were dropped (estimation) dup How many packets were duplicated. out_of_order How many packets we received out of order. seq_too_high How many events of packet with sequence number too high we saw. seq_too_low How many events of packet with sequence number too low we saw. For calculating packet error events, we add sequence number to each packet’s payload. We decide what went wrong only according to sequence number of last packet received and that of the previous packet. ‘seq_too_low’ and ‘seq_too_high’ count events we see. ‘dup’, ‘out_of_order’ and ‘dropped’ are heuristics we apply to try and understand what happened. They will be accurate in common error scenarios. We describe few scenarios below to help understand this.
Scenario 1: Received packet with seq num 10, and another one with seq num 10. We increment ‘dup’ and ‘seq_too_low’ by 1.
Scenario 2: Received pacekt with seq num 10 and then packet with seq num 15. We assume 4 packets were dropped, and increment ‘dropped’ by 4, and ‘seq_too_high’ by 1. We expect next packet to arrive with sequence number 16.
Scenario 2 continue: Received packet with seq num 11. We increment ‘seq_too_low’ by 1. We increment ‘out_of_order’ by 1. We decrement ‘dropped’ by 1. (We assume here that one of the packets we considered as dropped before, actually arrived out of order).
latency
key Meaning average Average latency over the stream lifetime (usec).Low pass filter is applied to the last window average.It is computed each sampling period by following formula: <average> = <prev average>/2 + <last sampling period average>/2 histogram Dictionary describing logarithmic distribution histogram of packet latencies. Keys in the dictionary represent range of latencies (in usec). Values are the total number of packets received in this latency range. For example, an entry {100:13} would mean that we saw 13 packets with latency in the range between 100 and 200 usec. jitter Jitter of latency samples, computed as described in RFC 3550#appendix-A.8 last_max Maximum latency measured between last two data reads from server (0.5 sec window). total_max Maximum latency measured over the stream lifetime (in usec). total_min Minimum latency measured over the stream lifetime (in usec). global latency stats dictionary has the following structure:
key Meaning old_flow Number of latency statistics packets received that we could not associate to any pg_id. This can happen if latency on the used setup is large. See wait_on_traffic rx_delay_ms parameter for details. bad_hdr Number of latency packets received with bad latency data. This can happen becuase of garbage packets in the network, or if the DUT causes packet corruption. raises: TRexError
-
service_line(line)[source]¶ Configures port for service mode. In service mode ports will reply to ARP, PING and etc.
-
arp(ports=None, retries=0, verbose=True, vlan=None)¶ Resolves ports (ARP resolution)
Parameters: - ports: list
List of port IDs to resolve
- retries: int
How many times to retry on each port (intervals of 100 milliseconds)
- verbose: bool
Log for each request the response
- vlan: int or list of ints
One or two VLAN tags o.w it will be taken from the src port configuration
Raises: - :exe:’TRexError’
-
clear_events()¶ Clear all events
Parameters: None Raises: None
-
clear_stats_line(line)¶ Clear cached local statistics
-
clear_vlan(ports=None)¶ Clear any VLAN configuration on the port
Parameters: - ports: int
On which ports to clear VLAN config
Raises: TRexError
-
conf_ipv6(port, enabled, src_ipv6=None)¶ Configure IPv6 of port.
Parameters: - port: uint8_t
The port to disable ipv6
- enabled: bool
Wherever IPv6 should be enabled
- src_ipv6: string
Src IPv6 of port or empty string for auto-address
Raises: TRexError
-
conf_ipv6_line(line)¶ Configures IPv6 of a port
-
connect()¶ Connects to the TRex server
Parameters: None
Raises: TRexError
-
connect_line(line)¶ Connects to the TRex server and acquire ports
-
create_service_ctx(port)¶ Generates a service context. Services can be added to the context, and then executed
-
disconnect(stop_traffic=True, release_ports=True)¶ Disconnects from the server
Parameters: - stop_traffic : bool
Attempts to stop traffic before disconnecting.
- release_ports : bool
Attempts to release all the acquired ports.
-
disconnect_line(line)¶ Disconnect from the TRex server
-
fetch_capture_packets(capture_id, output, pkt_count=1000)¶ Fetch packets from existing active capture
Parameters: - capture_id: int
an active capture ID
- output: str / list
if output is a ‘str’ - it will be interpeted as output filename if it is a list, the API will populate the list with packet objects
in case ‘output’ is a list, each element in the list is an object containing: ‘binary’ - binary bytes of the packet ‘origin’ - RX or TX origin ‘ts’ - timestamp relative to the start of the capture ‘index’ - order index in the capture ‘port’ - on which port did the packet arrive or was transmitted from
- pkt_count: int
maximum packets to fetch
Raises: - :exe:’TRexError’
-
get_acquired_ports()¶ Parameters: None Returns: list of all acquired ports Raises: None
-
get_active_ports(owned=True)¶ Parameters: - owned - bool
if ‘True’ apply only-owned filter
Returns: List of all active ports
Raises: None
-
get_all_ports()¶ Parameters: None Returns: List of all ports Raises: None
-
get_capture_status()¶ Returns a dictionary where each key is an capture ID Each value is an object describing the capture
-
get_connection_info()¶ Parameters: None Returns: Connection dict Raises: None
-
get_events(ev_type_filter=None)¶ returns list of the events recorded
Parameters: - ev_type_filter: list
combination of: ‘warning’, ‘info’
Returns: warning logged events
Raises: None
-
get_events_line(line)¶ Shows events log
-
get_info()¶ returns all the info logged events
Parameters: None Returns: info logged events Raises: None
-
get_paused_ports(owned=True)¶ Parameters: - owned - bool
if ‘True’ apply only-owned filter
Returns: List of all paused ports
Raises: None
-
get_port(port_id)¶ Parameters: port_id - int Returns: Port object Raises: None
-
get_port_attr(port)¶ get the port attributes currently set
Parameters: port - for which port to return port attributes
Raises: - :exe:’TRexError’
-
get_port_count()¶ Parameters: None Returns: Number of ports Raises: None
-
get_resolvable_ports()¶ Parameters: None Returns: List of all resolveable ports (configured with L3 mode) Raises: None
-
get_resolved_ports()¶ Parameters: None Returns: List of all resolved ports Raises: None
-
get_server_supported_cmds()¶ Parameters: None Returns: List of commands supported by server RPC Raises: None
-
get_server_system_info()¶ Parameters: None Returns: Connection dict Raises: None
-
get_server_version()¶ Parameters: None Returns: Connection dict Raises: None
-
get_service_enabled_ports(owned=True)¶ Parameters: - owned - bool
if ‘True’ apply only-owned filter
Returns: List of all ports
Raises: None
-
get_service_filtered_ports(owned=True)¶ Parameters: - owned - bool
if ‘True’ apply only-owned filter
Returns: List of all ports at filtered service mode
Raises: None
-
get_transmitting_ports(owned=True)¶ Parameters: - owned - bool
if ‘True’ apply only-owned filter
Returns: List of all transmitting ports
Raises: None
-
get_util_stats()¶ Get utilization stats as dictionary with 2 keys: ‘cpu’ and ‘mbuf_stats’.
TRex CPU utilization and ports per core (list of dictionaries per core) Each dictionary contains two keys: 1. ‘ports’: The ports that the core is using. Idle ports are denoted by -1. 2. ‘history’: List of last 20 utilization values. Each value is calculated as average in interval of second.
MBUFs memory consumption per CPU socket.
Parameters: None
Raises: TRexError
-
get_verbose()¶ Get the verbose mode
Parameters: none Returns: Get the verbose mode as Bool Raises: None
-
get_warnings()¶ returns all the warnings logged events
Parameters: None Returns: warning logged events Raises: None
-
get_xstats(port_id)¶ Get extended stats of port: all the counters as dict.
Parameters: port_id: int
Returns: Dict with names of counters as keys and values of uint64. Actual keys may vary per NIC.
Raises: TRexError
-
global_cfg_line(line)¶ Set global configuration parameters
-
has_events()¶ returns True in case there are events in the queue
Raises: None
-
is_all_ports_acquired()¶ - is_all_ports_acquired
Parameters: None Returns: Returns True if all ports are acquired Raises: None
-
is_async_results_ready(port)¶ return True if the namsspace batch commnand was finished. need to call wait_for_async_results to get the resutl
for example:
while True: if c.is_async_results_ready(0): res = c.wait_for_async_results(0) break;
-
is_connected()¶ Parameters: None Returns: True if the connection is established to the server o.w False Raises: None
-
is_traffic_active(ports=None)¶ Return if specified port(s) have traffic
Parameters: - ports : list
Ports on which to execute the command
Raises: - :exe:’TRexError’
-
logger¶ Get the associated logger
Parameters: none Returns: Logger object Raises: None
-
map_line(line)¶ Maps ports topology
-
map_ports(ports=None, read_delay=0.3, send_pkts=3)¶ Get mapping of ports (connectivity)
Parameters: - ports: list
For which ports to apply a queue, default is all acquired ports
- read_delay: float
Delay in sec between sending packets and looking at received results
- send_pkts: int
How much packets to send from each port
Raises: - :exe:’TRexError’
-
namespace_remove_all(ports=None)¶ remove all namespaces from all ports
Parameters: - ports: list
The port(s) to remove all the namespaces
Raises: TRexError
-
ns_line(line)¶ Network namespace
-
ping_ip(src_port, dst_ip, pkt_size=64, count=5, interval_sec=1, vlan=None, **kw)¶ Pings an IP address through a port
Parameters: - src_port: int
On which port_id to send the ICMP PING request
- dst_ip: string
Which IP to ping
- pkt_size: int
Packet size to use
- count: int
How many times to ping
- interval_sec: float
how much time to wait between pings
- vlan: int or list of ints
One or two VLAN tags o.w it will be taken from the src port configuration
Returns: List of replies per ‘count’
Each element is dictionary with following items:
Always available keys:
- formatted_string - string, human readable output, for example: ‘Request timed out.’
- status - string, one of options: ‘success’, ‘unreachable’, ‘timeout’
Available only if status is ‘success’:
- src_ip - string, IP replying to request
- rtt - float, latency of the ping (round trip time)
- ttl - int, time to live in IPv4 or hop limit in IPv6
Raises: TRexError
-
ping_line(line)¶ Pings the server / specific IP
-
ping_rpc_server()¶ Pings the RPC server
Parameters: None
Returns: Timestamp of server
Raises: TRexError
-
pkt_line(line)¶ Sends a Scapy format packet
-
pop_event()¶ returns event from the head of the queue
Raises: None
-
probe_server()¶ Probe the server for the version / mode
Can be used to determine stateless or advanced statefull mode
Parameters: none Returns: dictionary describing server version and configuration Raises: None
-
push_packets(pkts, ports=None, force=False, ipg_usec=0)¶ Pushes a list of packets to the server a ‘packet’ can be anything with a bytes representation such as Scapy object, a simple string, a byte array and etc.
Total size, as for PCAP pushing is limited to 1MB unless ‘force’ is specified
Parameters: - pkts: scapy pkt or a list of scapy pkts
Data to send
- ports: list of ints
On which ports to push the packets
- force: bool
Ignore size higer than 1 MB
- ipg_usec: float
IPG in usec
-
remove_all_captures()¶ Removes any existing captures
-
remove_rx_queue(ports=None)¶ Removes RX queue from port(s)
Parameters: - ports: list
for which ports to remove the RX queue
Raises: - :exe:’TRexError’
-
resolve(ports=None, retries=0, verbose=True, vlan=None)¶ Resolves ports (ARP resolution)
Parameters: - ports: list
List of port IDs to resolve
- retries: int
How many times to retry on each port (intervals of 100 milliseconds)
- verbose: bool
Log for each request the response
- vlan: int or list of ints
One or two VLAN tags o.w it will be taken from the src port configuration
Raises: - :exe:’TRexError’
-
resolve_line(line)¶ Performs a port ARP resolution
-
scan6(ports=None, timeout=3, verbose=False)¶ Search for IPv6 devices on ports
Parameters: - ports: list
List of port IDs at which ports to run scan6
- timeout: float
how much time to wait for responses
- verbose: bool
log for each request the response
Returns: list of dictionaries per neighbor:
- type - type of device: ‘Router’ or ‘Host’
- mac - MAC address of device
- ipv6 - IPv6 address of device
Raises: - :exe:’TRexError’
-
scan6_line(line)¶ Search for IPv6 neighbors
-
server_shutdown(force=False)¶ Sends the server a request for total shutdown
Parameters: - force: bool
Shutdown server even if some ports are owned by another user
Raises: TRexError
-
set_bird_node(node_port, mac, ipv4=None, ipv4_subnet=None, ipv6_enabled=None, ipv6=None, ipv6_subnet=None, vlans=None, tpids=None, mtu=None)¶ a utility function that works on top of
set_namespace_start()andwait_for_async_results()batch operation API. the function creates a “bird node” using veth’s in bird namespace in trex.usage example:
c.set_bird_node(node_port = 0, mac = "00:00:00:01:00:06", ipv4 = "1.1.1.3", ipv4_subnet = 24, ipv6_enabled = True, ipv6_subnet = 124, vlans = [22], tpids = [0x8100])
Parameters: - node_port: int
Port id to set the bird node on
- mac: string
Mac address for the new bird node in format xx:xx:xx:xx:xx:xx
- ipv4: string
Ipv4 address for the new bird node
- ipv4_subnet: int
Ipv4 subnet for the new bird node
- ipv6_enabled: bool
True/False if ipv6 enabled on the new node, mandatory for ipv6 config
- ipv6: string
Ipv6 address for the new bird node
- ipv6_subnet: int
Ipv6 subnet for the new bird node
- vlans: list
Array of up to 2 uint16 tags.
- tpids: list
Array of tpidss that correspond to vlans. Default is [0x8100] in case of single VLAN and [0x88a8, 0x8100] in case of QinQ.
- mtu: int
MTU for bird node.
Raises: TRexErrorin case of any error
-
set_capture_port_bpf_filter(port, bpf_filter)¶ Set the BPF filter for the capture port
Parameters: - port: int
The port to change the filter of the capture port
- bpf_filter: string
The new BPF filter (empty disables the filter)
Raises: TRexError
-
set_global_cfg(params)¶ Change global configuration parameters.
Parameters: - params: dictionary
dictionary of global configuration parameters. Available parameters: “sched_max_stretch”, type = double, default =0.0, units = usec, scheduler’s maximum time for stretch in case it is a high value there won’t be a scheduler compensation on burst and time will not be stretch. 0.0 means use the default internal value (~100usec). value could not be lower than 100usec will be considered as 100usec.
Raises: TRexError
-
set_l2_mode(port, dst_mac)¶ Sets the port mode to L2
Parameters: - port: int
Port ID to set the dest address
- dst_mac: string
Destination MAC
Raises: TRexError
-
set_l2_mode_line(line)¶ Configures a port in L2 mode
-
set_l3_mode(port, src_ipv4, dst_ipv4, vlan=None)¶ Sets the port mode to L3
Parameters: - port: int
Port ID to set the addresses
- src_ipv4: string
IPv4 source address for the port
- dst_ipv4: string
IPv4 destination address
- vlan: int or list of ints
VLAN configuration
Raises: TRexError
-
set_l3_mode_line(line)¶ Configures a port in L3 mode
-
set_namespace(port, method, **args)¶ a utility function that works on top of
set_namespace_start()andwait_for_async_results()batch operation API. it creates a batch of one command and one result. It is good for slow operations that require blocking (such as get API)the function calls:
c.set_namespace_start(Obj(method, args)) r=c.wait_for_async_results() return (r)
usage example:
r=set_namespace(port=0,method='get_nodes')
Parameters: - port: int
Port ID to set the dest address
- method: string
method name. see NSCmds object for method names
- args: dict
method args
Raises: TRexErrorin case of any error
-
set_namespace_start(port, ns_cmds)¶ Start namespace batch operation. This commands is a batch command that interact with the kernel and could be slow in case of a big batch. use wait_for_async_results to block for the response, or is_async_results_ready to pool if the results is ready. see see
trex.common.trex_ns.NSCmdsandtrex.common.trex_ns.NSCmdResultUsing other Python API while there is an active batch is not recommended:
c.set_namespace_start(port=0, ns_cmds) res = c.wait_for_async_results(port=0);
Parameters: - port: int
Port ID to set the dest address
ns_cmds : see
trex.common.trex_ns.NSCmdsobjects that includes batch commandsRaises: TRexError
-
set_port_attr(ports=None, promiscuous=None, link_up=None, led_on=None, flow_ctrl=None, multicast=None, vxlan_fs=None)¶ Set port attributes
Parameters: - promiscuous: bool
Promiscuous mode
- link_up: bool
Link status
- led_on: bool
LED of port
- flow_ctrl: int
0: disable all, 1: enable tx side, 2: enable rx side, 3: full enable
- multicast: bool
Enable receiving multicast
- vxlan_fs: list
- UDP ports for which HW flow stats will be read from layers after VXLANUDP(<dst_port>)/VXLAN()/Ether()/... <— NIC will look for flow stats magic hereLimited only to supported NICs (currently i40e)
Raises: - :exe:’TRexError’
-
set_port_attr_line(line)¶ Sets port attributes
-
set_rx_queue(ports=None, size=1000)¶ Sets RX queue for port(s) The queue is cyclic and will hold last ‘size’ packets
Parameters: - ports: list
For which ports to apply a queue
- size: int
size of the queue
Raises: - :exe:’TRexError’
-
set_service_mode_base(ports=None, enabled=True, filtered=False, mask=None)¶ Set service mode for port(s) In service mode ports will respond to ARP, PING and etc. “enable” and “filtered” are mutual exclusive, choose 1 of them or none
Parameters: - ports: list
For which ports to configure service mode on/off
- enabled: bool
True for activating service mode, False for disabling. Mutual exclusive with “filtered”
- filtered: bool
True for activating service filtered mode, False for disabling. Mutual exclusive with “enabled”
- mask: int
Mask to apply on each port in ports while filtered mode is on. Only packets that are correspond to the port mask will be transferred. Masks flags: NO_MASK = 0 NO_TCP_UDP_MASK = 1 BGP_MASK = 2 DHCP_MASK = 4 TRANSPORT = 8 MDNS = 16 ALL_MASK = 255
Raises: - :exe:’TRexError’
-
set_timeout(timeout_sec)¶ Set timeout for connectivity to TRex server. Must be not connected.
Parameters: - timeout_sec : int or float
- Timeout in seconds for sync operations.If async data does not arrive for this period, disconnect.
Raises: TRexError- in case client is already connected.
-
set_verbose(level)¶ Sets verbose level
Parameters: - level : str
“none” - be silent no matter what “critical” “error” - show only errors (default client mode) “warning” “info” “debug” - print everything
Raises: None
-
set_vlan(ports=None, vlan=None)¶ Sets the port VLAN. VLAN tagging will be applied to control traffic such as ARP resolution of the port and periodic gratidious ARP
Parameters: - ports: list
The port(s) to set the vlan
- vlan: either None, int or a list of up to two ints
each value representing a VLAN tag when two are supplied, provide QinQ tagging. The first TAG is outer and the second is inner
Raises: TRexError
-
set_vlan_line(line)¶ Configures VLAN tagging for a port. control generated traffic such as ARP will be tagged
-
shutdown_line(line)¶ Shutdown the server
-
start_capture(tx_ports=None, rx_ports=None, limit=1000, mode='fixed', bpf_filter='')¶ Starts a low rate packet capturing on the server
Parameters: - tx_ports: list
on which ports to capture TX
- rx_ports: list
on which ports to capture RX
- limit: int
limit how many packets will be written memory requierment is O(9K * limit)
- mode: str
‘fixed’ - when full, newer packets will be dropped ‘cyclic’ - when full, older packets will be dropped
- bpf_filter: str
A Berkeley Packet Filter pattern Only packets matching the filter will be appended to the capture
Returns: returns a dictionary: {‘id: <new_id>, ‘ts’: <starting timestamp>}
where ‘id’ is the new capture ID for future commands and ‘ts’ is that server monotonic timestamp when the capture was created
Raises: - :exe:’TRexError’
-
start_capture_port(port, endpoint, bpf_filter=None)¶ Enable capture port to receive/send raw packets directly on a ZeroMQ Pair socket.
The ZeroMQ socket should already be bound to the endpoint passed to this function. The TRex server will then connect to this endpoint and start sending all the packets that matches the given BPF filter received on the provided port, on that socket. Any packet sends from the client to the TRex server on that ZeroMQ socket will also be sent as ‘raw’ packet on the specified port.
Parameters: - port: int
The port to activate the capture port on
- endpoint: string
The path to the endpoint to use to bind the socket (e.g. ipc:///tmp/my_endpoint) Should be unique and already bound to a PAIR ZeroMQ socket type. See ZMQ_PAIR in http://api.zeromq.org/4-0:zmq-socket
- bpf_filter: string
The BPF filter to use before sending packet on the ZeroMQ socket. It can be empty for no filter.
Raises: TRexError
-
stop_capture(capture_id, output=None)¶ Stops an active capture and optionally save it to a PCAP file
Parameters: - capture_id: int
an active capture ID to stop
- output: None / str / list
if output is None - all the packets will be discarded if output is a ‘str’ - it will be interpeted as output filename if it is a list, the API will populate the list with packet objects
in case ‘output’ is a list, each element in the list is an object containing: ‘binary’ - binary bytes of the packet ‘origin’ - RX or TX origin ‘ts’ - timestamp relative to the start of the capture ‘index’ - order index in the capture ‘port’ - on which port did the packet arrive or was transmitted from
Raises: - :exe:’TRexError’
-
stop_capture_port(port)¶ Disable capture port
Parameters: - port: int
The port to stop the capture port on
Raises: TRexError
-
wait_for_async_results(port, timeout=None, cb=None)¶ wait for the namespace batch operations to finish, return an a list of batch results it includes something like that [None, {‘u’error’:’some error’},{u’result’: {u’nodes’: [u’’]}}
None : means that there is no error and command was executed object: that include ‘error’ means that there is an error object with ‘result’
Parameters: - port: int
Port ID to set the dest address
timeout : in second, None is unlimited
cb: A callback function that gets an object for calculating progress of a log operation
exec_cmds: total commands executed total_cmds: total commands in the queue errs_cmds: number of errors in the last operation ticket_id: ticket id
this will print the progress into the screen:
def progress_cb(obj): prog = 100.0*( float(obj['exec_cmds']) / float(obj['total_cmds'])) err = obj['errs_cmds'] print("progress {:3.0f}% errors : {}".format(prog,err))
Raises: TRexErrorin case of any error
STLClient snippet¶
# Example 1: Minimal example of client interacting with the TRex server
c = STLClient()
try:
# connect to server
c.connect()
# prepare our ports (my machine has 0 <--> 1 with static route)
c.reset(ports = [0, 1])
# add both streams to ports
c.add_streams(s1, ports = [0])
# clear the stats before injecting
c.clear_stats()
c.start(ports = [0, 1], mult = "5mpps", duration = 10)
# block until done
c.wait_on_traffic(ports = [0, 1])
# check for any warnings
if c.get_warnings():
# handle warnings here
pass
finally:
c.disconnect()
# Example 2: Client can execute other functions while the TRex server is generating traffic
c = STLClient()
try:
#connect to server
c.connect()
#..
c.start(ports = [0, 1], mult = "5mpps", duration = 10)
# block until done
while True :
# do somthing else
os.sleep(1) # sleep for 1 sec
# check if the port is still active
if c.is_traffic_active(ports = [0, 1])==False
break;
finally:
c.disconnect()
# Example 3: Console-like API interface
def simple ():
# create client
c = STLClient(verbose_level = "error")
passed = True
try:
# connect to server
c.connect()
my_ports=[0,1]
# prepare our ports
c.reset(ports = my_ports)
print (" is connected {0}".format(c.is_connected()))
print (" number of ports {0}".format(c.get_port_count()))
print (" acquired_ports {0}".format(c.get_acquired_ports()))
# port stats
print c.get_stats(my_ports)
# port info, mac-addr info, speed
print c.get_port_info(my_ports)
c.ping()
print("start")
# start traffic on port 0,1 each 10mpps
c.start_line (" -f ../../../../stl/udp_1pkt_simple.py -m 10mpps --port 0 1 ")
time.sleep(2);
c.pause_line("--port 0 1");
time.sleep(2);
c.resume_line("--port 0 1");
time.sleep(2);
c.update_line("--port 0 1 -m 5mpps"); # reduce to 5 mpps
time.sleep(2);
c.stop_line("--port 0 1"); # stop both ports
except STLError as e:
passed = False
print e
finally:
c.disconnect()
Example 4: Load profile from a file:
def simple ():
# create client
c = STLClient(verbose_level = "error")
passed = True
try:
# connect to server
c.connect()
my_ports=[0,1]
# prepare our ports
c.reset(ports = my_ports)
profile_file = "../../../../stl/udp_1pkt_simple.py" # a traffic profile file
try: # load a profile
profile = STLProfile.load(profile_file)
except STLError as e:
print format_text("\nError while loading profile '{0}'\n".format(profile_file), 'bold')
print e.brief() + "\n"
return
print profile.dump_to_yaml() # print it as YAML
c.remove_all_streams(my_ports) # remove all streams
c.add_streams(profile.get_streams(), ports = my_ports) # add them
c.start(ports = [0, 1], mult = "5mpps", duration = 10) # start for 10 sec
# block until done
c.wait_on_traffic(ports = [0, 1]) # wait
finally:
c.disconnect()
# Example 5: pin cores to ports
c = STLClient()
try:
# connect to server
c.connect()
# prepare our ports (my machine has 0 <--> 1 with static route)
c.reset(ports = [0, 1])
# add both streams to ports
c.add_streams(s1, ports = [0])
# clear the stats before injecting
c.clear_stats()
c.start(ports = [0, 1], mult = "5mpps", duration = 10, core_mask = [0x1,0x2]) # pin core to ports for better performance
# block until done
c.wait_on_traffic(ports = [0, 1])
# check for any warnings
if c.get_warnings():
# handle warnings here
pass
finally:
c.disconnect()