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 = 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
usernamestring

the user name, for example imarom

serverstring

the server name or ip

sync_portint

the RPC port

async_portint

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

get_mode()[source]

return the mode/type for the client

reset(ports=None, restart=False)[source]

Force acquire ports, stop the traffic, remove all streams and clear stats

Parameters
portslist

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
portslist

Ports on which to execute the command

forcebool

Force acquire the ports.

sync_streams: bool

sync with the server about the configured streams

Raises
  • TRexError

release(ports=None)[source]

Release ports

Parameters
portslist

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
portslist

Ports on which to execute the command

Raises
  • TRexError

add_streams(streams, ports=None)[source]

Add a list of streams to port(s)

Parameters
portslist

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
filenamestring

filename (with path) of the profile

portslist

list of ports to add the profile (default: all acquired)

kwargsdict

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

portslist

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
portslist

Ports on which to execute the command

multstr

Multiplier in a form of pps, bps, or line util in % Examples: “5kpps”, “10gbps”, “85%”, “32mbps”

forcebool

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

durationint

Limit the run time (seconds) -1 = unlimited

totalbool

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 synchronized. Must use adjacent ports (belong to same set of cores). Will set default core_mask to 0x1. Recommended ipg 1ms and more.

Raises
  • TRexError

start_stl(ports=None, mult='1', force=False, duration=- 1, total=False, core_mask=None, synchronized=False)

Start traffic on port(s)

Parameters
portslist

Ports on which to execute the command

multstr

Multiplier in a form of pps, bps, or line util in % Examples: “5kpps”, “10gbps”, “85%”, “32mbps”

forcebool

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

durationint

Limit the run time (seconds) -1 = unlimited

totalbool

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 synchronized. 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
portslist

Ports on which to execute the command

rx_delay_msint

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

stop_stl(ports=None, rx_delay_ms=None)

Stop port(s)

Parameters
portslist

Ports on which to execute the command

rx_delay_msint

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
portslist

Ports on which to execute the command

timeoutint

timeout in seconds default will be blocking

rx_delay_msint

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
portslist

Ports on which to execute the command

multstr

Multiplier in a form of pps, bps, or line util in % Can also specify +/- Examples: “5kpps+”, “10gbps-”, “85%”, “32mbps”, “20%+”

forcebool

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

totalbool

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_stl(ports=None, mult='1', total=False, force=False)

Update traffic on port(s)

Parameters
portslist

Ports on which to execute the command

multstr

Multiplier in a form of pps, bps, or line util in % Can also specify +/- Examples: “5kpps+”, “10gbps-”, “85%”, “32mbps”, “20%+”

forcebool

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

totalbool

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
portint

Port on which to execute the command

multstr

Multiplier in a form of pps, bps, or line util in % Examples: “5kpps”, “10gbps”, “85%”, “32mbps”

forcebool

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
portslist

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
portint

Port on which to execute the command

stream_idslist

Stream IDs to pause

Raises
  • TRexError

resume(ports=None)[source]

Resume traffic on port(s)

Parameters
portslist

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
portint

Port on which to execute the command

stream_idslist

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_filenamestr

PCAP file name in full path and accessible to the server

portslist

Ports on which to execute the command

ipg_usecfloat

Inter-packet gap in microseconds. Exclusive with min_ipg_usec

speedupfloat

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_usecfloat

Minimum inter-packet gap in microseconds to guard from too small ipg. Exclusive with ipg_usec

forcebool

Ignore if port is active

src_mac_pcapbool

Source MAC address will be taken from pcap file if True.

dst_mac_pcapbool

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_filenamestr

PCAP filename (accessible locally)

portslist

Ports on which to execute the command

ipg_usecfloat

Inter-packet gap in microseconds. Exclusive with min_ipg_usec

speedupfloat

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_hookCallable 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_usecfloat

Minimum inter-packet gap in microseconds to guard from too small ipg. Exclusive with ipg_usec

src_mac_pcapbool

Source MAC address will be taken from pcap file if True.

dst_mac_pcapbool

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 occurred 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 packet 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 because of garbage packets in the network, or if the DUT causes packet corruption.

raises
  • TRexError

enable_tpg(num_tpgids, tags, rx_ports=None)[source]

Enable Tagged Packet Grouping.

This method has 3 phases:

  1. Enable TPG in Control Plane and send message to Rx to allocate memory.

  2. Wait until Rx finishes allocating.

  3. Enable the feature in Data Plane.

Parameters
num_tpgids: uint32

Number of Tagged Packet Groups that we are expecting to send. The number is an upper bound, and tpgids should be in [0, num_tpgids).

Note

This number is important in allocating server memory, hence be careful with it.

tags: list

List of dictionaries that represents the mapping of actual tags to tag ids.

[
    {
        "type": "Dot1Q",
        "value": {
            "vlan": 5,
        }
    },
    {
        "type": "QinQ",
        "value": {
            "vlans": [20, 30]
        }
    }
]

Currently supports only Dot1Q, QinQ tags. In our example, Dot1Q (5) is mapped to tag id 0, and QinQ (20, 30) is mapped to tag id 1 and so on.

Each dictionary should be of the following format:

key

Meaning

type

String that represents type of tag, only Dot1Q and QinQ supported at the moment.

value

Dictionary that contains the value for the tag. Differs on each tag type.

rx_ports: list

List of rx ports on which we gather Tagged Packet Group Statistics. Optional. If not provided, data will be gathered on all acquired ports.

disable_tpg(username=None, surpress_log=False)[source]

Disable Tagged Packet Grouping.

This method has 2 phases.

  1. Disable TPG in DPs and Cp. Send a message to Rx to start deallocating.

  2. Wait until Rx finishes deallocating.

Parameters
username: string

Username whose TPG context we want to disable. Optional. If not provided, we disable for the calling user.

surpress_log: bool

Surpress logs, in case disable TPG is run as a subroutine. Defaults to False.

get_tpg_status(username=None, port=None)[source]

Get Tagged Packet Group Status from the server. We can collect the TPG status for a user or for a port. If no parameters are provided we will collect for the calling user.

Note

Only one between username and port should be provided.

Parameters
username: str

Username whose TPG status we want to check. Optional. In case it isn’t provided, the username that runs the command will be used.

port: uint8

Port whose TPG status we want to check. Optional.

Returns

dict: Tagged Packet Group Status from the server. The dictionary contains the following keys:

{
    "enabled": true,
    "data": {
        "rx_ports": [1],
        "acquired_ports": [0, 1],
        "num_tpgids": 3,
        "num_tags": 10,
        "username": "bdollma"
    }
}

key

Meaning

enabled

Boolean indicated if TPG is enabled/disabled.

rx_ports

Ports on which TPG is collecting stats. Relevant only if TPG is enabled.

acquired_ports

Ports on which TPG can transmit. Relevant only if TPG is enabled.

num_tpgids

Number of Tagged Packet Groups. Relevant only if TPG is enabled.

num_tags

Number of Tagged Packet Group Tags. Relevant only if TPG is enabled.

username

User that owns this instance of TPG. Relevant only if TPG is enabled.

update_tpg_tags(new_tags, clear=False)[source]

Update Tagged Packet Grouping Tags.

Parameters
new_tags: list

List of dictionaries that represents the tags to replace.

[
    {
        "type": "Dot1Q",
        "value": {
            "vlan": 5,
        }
        "tag_id": 20
    },
    {
        "type": "QinQ",
        "value": {
            "vlans": [20, 30]
        }
        "tag_id": 7
    },
    {
        "type": None,
        "tag_id": 0
    }
]

Currently supports only Dot1Q, QinQ, None types. In our example, tag_id 20 is now replaced with Dot1Q(5). Note that Dot1Q(5) must not be present, or at least invalidated in one of the previous entries. When the type is None, it invalidates the tag.

Each dictionary should be of the following format:

key

Meaning

type

String that represents type of tag, only Dot1Q, QinQ or None supported at the moment.

value

Dictionary that contains the value for the tag. Differs on each tag type. Not needed in case of None.

tag_id

The tag id that this new tag is going to have.

clear: bool

Clear stats for the tags we updated. Defaults to False.

Note

This can take some time, since we need to clear the stats in all the receiveing ports for all tpgids.

get_tpg_tags(min_tag=0, max_tag=None, username=None, port=None)[source]

Get Tagged Packet Group Tags from the server. It will return as a list starting from min_tag until max_tag. If not provided, we will collect for all tags. We can collect the TPG status for a user or for a port. If no parameters are provided we will collect for the calling user.

Parameters
min_tag: int

Minimal tag to collect the tag for. Optional. If not provided, we will start from 0.

max_tag: int

Maximal tag to collect the tag for. Defaults to None. If not provided, we will collect for the max possible tag.

username: str

Username whose TPG status we want to check. Optional. In case it isn’t provided, the username that runs the command will be used.

port: uint8

Port whose TPG status we want to check. Optional.

Returns

list: Tagged Packet Group Tags from the server. At index i in the list we can find the descripton for tag number i. If the value is None, it means that this tag index was invalidated.

[
    {
        "type": "Dot1Q",
        "value": {
            "vlan": 7
        }
    },
    None,
    {
        "type": "QinQ",
        "value": {
            "vlans": [1, 11]
        }
    }
]

get_tpg_stats(port, tpgid, min_tag, max_tag, max_sections=50, unknown_tag=False, untagged=False)[source]

Get Tagged Packet Group statistics that are received in this port, for this Tagged Packet Group Identifier in [min, max) tag_range.

Parameters
port: uint8

Port on which we collect the stats.

tpgid: uint32

Tagged Packet Group Identifier whose stats we are interested to collect.

min_tag: uint16

Minimal Tag to collect stats for.

max_tag: uint16

Maximal Tag to collect stats for. Non inclusive.

max_sections: int

Maximal sections to collect in the stats. Defaults to 50.

Note

If we have the same stats for two consequent tags, their values will assembled into one section in order to compress the stats. The common use case is that stats are the same on each tag, hence the compression is effective.

If all the tags from [min-max) can be compressed in less than max_sections, we will get all tags from [min-max), otherwise we will get max_sections entries in the stats dictionary.

unknown_tag: bool

Get the stats of packets received with this tpgid but with a tag that isn’t provided in the mapping, i.e an unknown tag.

untagged: bool

Get the stats of packets received with this tpgid but without any tag.

Returns

(dict, uint16): Stats collected the next tag to start collecting from (relevant if not all the data was collected)

Dictionary contains Tagged Packet Group statistics gathered from the server. For example:

print(get_tpg_stats(port=3, tpgid=1, min_tag=0, max_tag=4000, unknown_tag=True)[0])

{'3': {'1': {
            '0-200': {'bytes': 0,
                      'dup': 0,
                      'ooo': 0,
                      'pkts': 0,
                      'seq_err': 0,
                      'seq_err_too_big': 0,
                      'seq_err_too_small': 0
                    },
            '201': {'bytes': 204,
                    'dup': 0,
                    'ooo': 0,
                    'pkts': 3,
                    'seq_err': 2,
                    'seq_err_too_big': 1,
                    'seq_err_too_small': 0},
            '202-3999': {'bytes': 0,
                         'dup': 0,
                         'ooo': 0,
                         'pkts': 0,
                         'seq_err': 0,
                         'seq_err_too_big': 0,
                         'seq_err_too_small': 0},
            'untagged': {'bytes': 0,
                         'dup': 0,
                         'ooo': 0,
                         'pkts': 0,
                         'seq_err': 0,
                         'seq_err_too_big': 0,
                         'seq_err_too_small': 0},
            'unknown_tag': {'bytes': 0,
                            'pkts': 0}}}}

The returned data is separated per port and per tpgid, so it can be easily merged with data from other ports/tpgids.

In this example we can see that all the data is compressed in 3 sections (excluding the unknown_tag and untagged.).

uint16: Indicates the next tag to start collecting from. In case all the tags were collected this will equal max_tag.

In case the user provided min_tag = max tag, the user collected only unknown or untagged, hence this will be None.

clear_tpg_stats(port, tpgid, min_tag=0, max_tag=None, tag_list=None, unknown_tag=False, untagged=False)[source]

Clear Packet Group Identifier statistics that are received in this port, for this Tagged Packet Group Identifier in [min, max) tag_range.

Parameters
port: uint8

Port on which we want to clear the stats.

tpgid: uint32

Tagged Packet Group Identifier whose stats we are interested to clear.

min_tag: uint16

Minimal Tag to clear stats for. Defaults to 0.

max_tag: uint16

Maximal Tag to clear stats for. Non inclusive. Defaults to None. Exclusive to tag_list.

tag_list: list or None

List of tags to clear, if provided takes precedence over the range [min-max). Exclusive to max_tag.

unknown_tag: bool

Clear the stats of packets received with this tpgid but with a tag that isn’t provided in the mapping, i.e an unknown tag.

untagged: bool

Clear the stats of packets received with this tpgid but without any tag.

get_tpg_tx_stats(port, tpgid)[source]

Get Tagged Packet Group Identifier statistics that are transmitted in this port, for this Tagged Packet Group Identifier.

Parameters
port: uint8

Port on which we transmit TPG packets.

tpgid: uint32

Tagged Packet Group Identifier

Returns

dict: Dictionary contains Tagged Packet Group statistics gathered from the server. For example:

print(get_tpg_tx_stats(port=0, tpgid=1))

{'0': 
    {'1': 
        { 'bytes': 0,
          'pkts': 0}}}

clear_tpg_tx_stats(port, tpgid)[source]

Clear Tagged Packet Group Identifier statistics that are transmitted in this port, for this Tagged Packet Group Identifier.

Parameters
port: uint8

Port on which we transmit TPG packets.

tpgid: uint32

Tagged Packet Group Identifier

get_tpg_unknown_tags(port)[source]

Get Tagged Packet Group Unknown tags found in this port.

Parameters
port: uint8

Port on which we collect TPG stats.

Returns

dict: Dictionary contains Tagged Packet Group unknown tags gathered on each port. For example:

print(get_tpg_unknown_tags(port=1)

{'1': [
    {'tag': {'type': 'Dot1Q', 'value': {'vlan': 12}}, 'tpgid': 12},
    {'tag': {'type': 'QinQ', 'value': {'vlans': [1, 100]}}, 'tpgid': 0},
    {'tag': {'type': 'Dot1Q', 'value': {'vlan': 11}}, 'tpgid': 11}
]}

clear_tpg_unknown_tags(port)[source]

Clear Tagged Packet Group Unknown tags found in this port.

Parameters
port: uint8

Port on which we collect TPG packets.

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

profiles_line(line)[source]

Get loaded to server profiles information

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

tpg_enable(line)[source]

Enable Tagged Packet Group

tpg_disable(line)[source]

Disable Tagged Packet Group

show_tpg_status(line)[source]

Show Tagged Packet Group Status

tpg_update(line)[source]

Update Tagged Packet Group Tag

show_tpg_tags(line)[source]

Show Tagged Packet Group Tags

show_tpg_stats(line)[source]

Show Tagged Packet Group Statistics

tpg_clear_stats(line)[source]

Clear Tagged Packet Group Stats

show_tpg_tx_stats(line)[source]

Show Tagged Packet Group Tx Statistics

tpg_clear_tx_stats(line)[source]

Clear Tagged Packet Group Tx Stats

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_trafficbool

Attempts to stop traffic before disconnecting.

release_portsbool

Attempts to release all the acquired ports.

disconnect_line(line)

Disconnect from the TRex server

endpoint_cb_rsync(output)

Return typical endpoint callback function with rsync

fetch_capture_packets(capture_id, output, pkt_count=1000, fetch_limit=50, snaplen=0)

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 snappled packet ‘wirelen’- length of the packet on the wire ‘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

fetch_limit: int

limit of packets to fetch with one _transmit() call

snaplen: int

snapshot length is the amount of data for each packet that is actually captured if snaplen is 0 - fetch the full length packet without snapshot

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

Get global configuration parameter values. See set_global_cfg for the parameters.

Raises
  • TRexError

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
portslist

Ports on which to execute the command

Raises
  • :exe:’TRexError’

property 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() and wait_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
  • TRexError in 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: double
The maximum time for scheduler stretch.

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. The change cannot be applied to the current epoch. Default = 0.0, Units = usec.

process_at_cp: bool
Enable parsing processing at CP core.

ASTF profile needs to prepare for traffic generation. By default, it is performed at DP cores. But when you run multiple profiles, since it consumes DP processing power, it may affect the traffic generation. This parameter can remove the process from DP cores and perform it at CP core. Default = False.

do_mbuf_cache: bool
Enable mbuf caching.

ASTF profile’s buffer can be filled with specific pattern. This parameter enables the cached mbuf for the same patterns. It will save 2K mbuf consumption when you run lots of profiles with the same patterns. But, since a pattern consumes a 2K mbuf permanently, please enable this parameter only the patterns are limited. Default = False.
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() and wait_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
  • TRexError in 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.NSCmds and trex.common.trex_ns.NSCmdResult

Using 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.NSCmds objects that includes batch commands

Raises
  • 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 VXLAN
UDP(<dst_port>)/VXLAN()/Ether()/… <— NIC will look for flow stats magic here
Limited 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_secint 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
levelstr

“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

show_tpg_unknown_stats(line)[source]

Show Tagged Packet Group Unknown Tags

shutdown_line(line)

Shutdown the server

start_capture(tx_ports=None, rx_ports=None, limit=1000, mode='fixed', bpf_filter='', endpoint='', snaplen=0)

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

endpoint: str

save the matched packets through the specified endpoint as PCAPNG format.

file endpoint - ‘file:///’ + ‘<filepath>’, it can be a directory or a file. ZMQ endpoint - ‘tcp://’ or ‘ipc://’ + <zmq recv server>

snaplen: int

maximum number of bytes dumped from each packet

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, endpoint_cb=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

endpoint_cb: function

a method to get the captured file from the server host in case capture_id started with ‘endpoint’ only the API will wait for flush done and call ‘endpoint_cb(endpoint)’

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
  • TRexError in case of any error

tpg_clear_unknown_stats(line)[source]

Clear Tagged Packet Group Unknown Tags

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