ASTF Client Module

The TRex Client provides access to the TRex server.

ASTFClient class

class trex.astf.trex_astf_client.ASTFClient(username='hhaim', server='localhost', sync_port=4501, async_port=4500, verbose_level='error', logger=None)[source]

TRex advance stateful 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(restart=False)[source]

Force acquire ports, stop the traffic, remove loaded traffic and clear stats

Parameters:
restart: bool

Restart the NICs (link down / up)

Raises:
  • TRexError
acquire(force=False)[source]

Acquires ports for executing commands

Parameters:
force : bool

Force acquire the ports.

Raises:
  • TRexError
release(force=False)[source]

Release ports

Parameters:

none

Raises:
  • TRexError
load_profile(profile, tunables={})[source]

Upload ASTF profile to server

Parameters:
profile: string or ASTFProfile

Path to profile filename or profile object

tunables: dict

forward those key-value pairs to the profile file

Raises:
  • TRexError
get_traffic_distribution(start_ip, end_ip, dual_ip, seq_split)[source]

Get distribution of IP range per TRex port per core

Parameters:
start_ip: IP string

Related to “ip_range” argument of ASTFIPGenDist

end_ip: IP string

Related to “ip_range” argument of ASTFIPGenDist

dual_ip: IP string

Related to “ip_offset” argument of ASTFIPGenGlobal

seq_split: bool

Related to “per_core_distribution” argument of ASTFIPGenDist, “seq” => seq_split=True

clear_profile()[source]

Clear loaded profile

start(mult=1, duration=-1, nc=False, block=True, latency_pps=0, ipv6=False, client_mask=4294967295)[source]

Start the traffic on loaded profile. Procedure is async.

Parameters:
mult: int

Multiply total CPS of profile by this value.

duration: float

Start new flows for this duration. Negative value means infinite

nc: bool

Do not wait for flows to close at end of duration.

block: bool

Wait for traffic to be started (operation is async).

latency_pps: uint32_t

Rate of latency packets. Zero value means disable.

ipv6: bool

Convert traffic to IPv6.

client_mask: uint32_t

Bitmask of enabled client ports.

Raises:
  • :exe:’TRexError’
stop(block=True)[source]

Stop the traffic.

Parameters:
block: bool

Wait for traffic to be stopped (operation is async) Default is True

Raises:
  • :exe:’TRexError’
update(mult)[source]

Update the rate of running traffic.

Parameters:
mult: int

Multiply total CPS of profile by this value (not relative to current running rate) Default is 1

Raises:
  • :exe:’TRexError’
wait_on_traffic(timeout=None)[source]

Block until traffic stops

Parameters:
timeout: int

Timeout in seconds Default is blocking

Raises:
  • TRexTimeoutError - in case timeout has expired
  • :exe:’TRexError’
is_traffic_stats_error(stats)[source]

Return Tuple if there is an error and what is the error (Bool,Errors)

Parameters:stats: dict from get_traffic_stats output
start_latency(mult=1, src_ipv4='16.0.0.1', dst_ipv4='48.0.0.1', ports_mask=2147483647, dual_ipv4='1.0.0.0')[source]

Start ICMP latency traffic.

parameters:
mult: float

number of packets per second

src_ipv4: IP string

IPv4 source address for the port

dst_ipv4: IP string

IPv4 destination address

ports_mask: uint32_t

bitmask of ports

dual_ipv4: IP string

IPv4 address to be added for each pair of ports (starting from second pair)

Note

VLAN will be taken from interface configuration

raises:
  • TRexError
stop_latency()[source]

Stop latency traffic.

update_latency(mult=1)[source]

Update rate of latency traffic.

parameters:
mult: float

number of packets per second

raises:
  • TRexError
topo_load(topology, tunables={})[source]

Load network topology

Parameters:
topology: string or ASTFTopology

Path to topology filename or topology object

tunables: dict

forward those key-value pairs to the topology file

Raises:
  • TRexError
topo_clear()[source]

Clear network topology

topo_resolve(ports=None)[source]

Resolve current network topology

topo_show(ports=None)[source]

Show current network topology status

topo_save(filename)[source]

Save current topology to file

acquire_line(line)[source]

Acquire ports

reset_line(line)[source]

Reset ports

start_line(line)[source]

start traffic command

stop_line(line)[source]

stop traffic command

update_line(line)[source]

update traffic multiplier

latency_line(line)[source]

Latency-related commands

topo_line(line)[source]

Topology-related commands

show_stats_line(line)[source]

Show various statistics

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

Set timeout for connectivity to TRex server. Must be not connected.

Parameters:
timeout_sec : int or float
Timeout in seconds for sync operations.
If async data does not arrive for this period, disconnect.
Raises:
  • TRexError - in case client is already connected.
set_verbose(level)

Sets verbose level

Parameters:
level : str

“none” - be silent no matter what “critical” “error” - show only errors (default client mode) “warning” “info” “debug” - print everything

Raises:

None

set_vlan(ports=None, vlan=None)

Sets the port VLAN. VLAN tagging will be applied to control traffic such as ARP resolution of the port and periodic gratidious ARP

Parameters:
ports: list

The port(s) to set the vlan

vlan: either None, int or a list of up to two ints

each value representing a VLAN tag when two are supplied, provide QinQ tagging. The first TAG is outer and the second is inner

Raises:
  • TRexError
set_vlan_line(line)

Configures VLAN tagging for a port. control generated traffic such as ARP will be tagged

shutdown_line(line)

Shutdown the server

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

Starts a low rate packet capturing on the server

Parameters:
tx_ports: list

on which ports to capture TX

rx_ports: list

on which ports to capture RX

limit: int

limit how many packets will be written memory requierment is O(9K * limit)

mode: str

‘fixed’ - when full, newer packets will be dropped ‘cyclic’ - when full, older packets will be dropped

bpf_filter: str

A Berkeley Packet Filter pattern Only packets matching the filter will be appended to the capture

Returns:

returns a dictionary: {‘id: <new_id>, ‘ts’: <starting timestamp>}

where ‘id’ is the new capture ID for future commands and ‘ts’ is that server monotonic timestamp when the capture was created

Raises:
  • :exe:’TRexError’
start_capture_port(port, endpoint, bpf_filter=None)

Enable capture port to receive/send raw packets directly on a ZeroMQ Pair socket.

The ZeroMQ socket should already be bound to the endpoint passed to this function. The TRex server will then connect to this endpoint and start sending all the packets that matches the given BPF filter received on the provided port, on that socket. Any packet sends from the client to the TRex server on that ZeroMQ socket will also be sent as ‘raw’ packet on the specified port.

Parameters:
port: int

The port to activate the capture port on

endpoint: string

The path to the endpoint to use to bind the socket (e.g. ipc:///tmp/my_endpoint) Should be unique and already bound to a PAIR ZeroMQ socket type. See ZMQ_PAIR in http://api.zeromq.org/4-0:zmq-socket

bpf_filter: string

The BPF filter to use before sending packet on the ZeroMQ socket. It can be empty for no filter.

Raises:
  • TRexError
stop_capture(capture_id, output=None)

Stops an active capture and optionally save it to a PCAP file

Parameters:
capture_id: int

an active capture ID to stop

output: None / str / list

if output is None - all the packets will be discarded if output is a ‘str’ - it will be interpeted as output filename if it is a list, the API will populate the list with packet objects

in case ‘output’ is a list, each element in the list is an object containing: ‘binary’ - binary bytes of the packet ‘origin’ - RX or TX origin ‘ts’ - timestamp relative to the start of the capture ‘index’ - order index in the capture ‘port’ - on which port did the packet arrive or was transmitted from

Raises:
  • :exe:’TRexError’
stop_capture_port(port)

Disable capture port

Parameters:
port: int

The port to stop the capture port on

Raises:
  • TRexError

ASTFClient snippet

c = ASTFClient(server = server)

c.connect()

try:
    c.reset()

    c.load_profile(profile_path)

    c.clear_stats()

    c.start(mult = mult, duration = duration, nc = True)

    c.wait_on_traffic()

    stats = c.get_stats()

    pprint.pprint(stats)

    if c.get_warnings():
        for w in c.get_warnings():
            print(w)


except TRexError as e:
    print(e)

except AssertionError as e:
    print(e)

finally:
    c.disconnect()
c = ASTFClient(server = server)

c.connect()

try:
    c.reset()

    c.load_profile(profile_full_path)

    c.clear_stats()

    c.start(mult = mult, duration = duration, nc = True)

    while c.is_traffic_active():
       stats = c.get_stats()
       # sample the stats
       time.sleep(1);

except Exception as e:
    print(e)

finally:
    c.disconnect()