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()

STLClient class

class trex.stl.trex_stl_client.STLClient(username='hhaim', server='localhost', sync_port=4501, async_port=4500, verbose_level='error', logger=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

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
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)[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

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)[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 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

Raises:
  • TRexError
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

reset_line(line)[source]

Reset ports

acquire_line(line)[source]

Acquire ports

release_line(line)[source]

Release ports

show_stats_line(line)[source]

Show various statistics

streams_line(line)[source]

Get loaded to server streams information

push_line(line)[source]

Push a pcap file

service_line(line)[source]

Configures port for service mode. In service mode ports will reply to ARP, PING and etc.

start_line(line)[source]

Start selected traffic on specified ports on TRex

stop_line(line)[source]

Stop active traffic on specified ports on TRex

update_line(line)[source]

Update port(s) speed currently active

pause_line(line)[source]

Pause active traffic on specified ports on TRex

resume_line(line)[source]

Resume active traffic on specified ports on TRex

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_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
is_all_ports_acquired()
is_all_ports_acquired
Parameters:None
Returns:Returns True if all ports are acquired
Raises:None
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’
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

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_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_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_port_attr(ports=None, promiscuous=None, link_up=None, led_on=None, flow_ctrl=None, resolve=True, multicast=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

resolve: bool

if true, in case a destination address is configured as IPv4 try to resolve it

multicast: bool

enable receiving multicast

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(ports=None, enabled=True)

Set service mode for port(s) In service mode ports will respond to ARP, PING and etc.

Parameters:
ports: list

for which ports to configure service mode on/off

enabled: bool

True for activating service mode, False for disabling

Raises:
  • :exe:’TRexError’
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

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()