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, sync_timeout=None, async_timeout=None)[source]¶
TRex advance stateful 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
- 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
- forcebool
Force acquire the ports.
- Raises
TRexError
- set_service_mode(ports=None, enabled=True, filtered=False, mask=None)[source]¶
based on
trex.astf.trex_astf_client.ASTFClient.set_service_mode_base()
- load_profile(profile, tunables={}, pid_input='_')[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
- pid_input: string
Input profile ID
- 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(block=True, pid_input='_')[source]¶
Clear loaded profile
- Parameters
- pid_input: string
Input profile ID
- Raises
TRexError
- start(mult=1, duration=- 1, nc=False, block=True, latency_pps=0, ipv6=False, pid_input='_', client_mask=4294967295, e_duration=0, t_duration=0, dump_interval=0)[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.
- pid_input: string
Input profile ID
- e_duration: float
Maximum time to wait for one flow to be established. Stop the flow generation when this time is over. Stop immediately with nc. Disabled by default. Enabled by positive values.
- t_duration: float
Maximum time to wait for all the flow to terminate gracefully after duration. Stop immediately (overrides nc pararmeter) when this time is over. Disabled by default. Enabled by non-zero values.
- dump_interval: float
Interval time for periodic dump of TCP flow information: RTT, CWND, etc. TCP flow dump enabled by non-zero values.
- Raises
TRexError
- stop(block=True, pid_input='_', is_remove=False)[source]¶
Stop the traffic.
- Parameters
- block: bool
Wait for traffic to be stopped (operation is async) Default is True
- pid_input: string
Input profile ID
- is_remove: bool
Remove the profile id Default is False
- Raises
TRexError
- update(mult, pid_input='_')[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
- pid_input: string
Input profile ID
- Raises
TRexError
- get_profiles(profiles_in_ports=False)[source]¶
Get profile list from Server.
- Parameters
- profiles_in_ports: bool
Get Stateless profiles also in all available ports Default is False
- Returns
List of profile names. When profiles_in_ports parameter is specified, a dictionary for all available ports is included in the list.
- get_flow_info(profile_id='_', duration=0, index=None)[source]¶
Get TCP flow information
- Parameters
- profile_id: string
Input profile ID
- duration: float
Requests stacked TCP flow information during duration time Default value is 0 which means one time request.
- index: int
Retreive TCP flow information from the index of stacked data to the last index. For the first call, use 0 for all stacked data. And the next call, use “next_index” value in flows from the previous result.
- Returns
dictionary of <flow_id> : [ <flow_info>, … ] pair. - <flow_id> is represented by “<src_ip>:<src_port>-<dst_ip>:<dst_port>”. - <flow_info> is dictionary that contains following key-value pairs.
”origin” : “client” or “server”
”duration” : elapsed time after established, msec as TCP timer resolution(10 msec)
- ”state”TCP state as a number.
0 - CLOSED, 1 - LISTEN, 2 - SYN_SENT, 3 - SYN_RECCEIVED, 4 - ESTABLISHED, 5 - CLOSE_WAIT, …
”options” : “/timestamps”, “/sack”, “/wscale”
”snd_wscale” : window scaling for send window, with “/wscale” only
”rcv_wscale” : window scaling for recv window, with “/wscale” only
”rto” : current retransmit value (msec)
”last_data_recv” : inactivity time (msec)
”rtt” : smoothed round-trip time, msec >> TCP_RTT_SHIFT(5)
”rttvar” : variance in round-trip time, msec >> TCP_RTTVAR_SHIFT(4)
”snd_ssthresh” : snd_cwnd size threshold for slow start exponential to linear switch
”snd_cwnd” : congestion-controlled window size
”rcv_space” : receive window size
”rcv_nxt” : receive next, distance value from initial receive sequence number
”snd_wnd” : send window size
”snd_nxt” : send next, distance value from initial send sequence number
”snd_mss” : maximum segment size
”rcv_mss” : maximum segment size
”snd_rexmitpack” : retransmit packets sent count
”rcv_ooopack” : out-of-order packets received count
”snd_zerowin” : zero-window updates sent count
When the index parameter is specified, “next_index” key is added as <flow_id>.
- Raises
TRexError
- wait_on_traffic(timeout=None, profile_id=None)[source]¶
Block until traffic stops
- Parameters
- timeout: int
Timeout in seconds Default is blocking
- profile_id: string
Profile ID
- Raises
TRexTimeoutError- in case timeout has expiredTRexError
- wait_on_traffic_stl(ports=None, timeout=None, rx_delay_ms=None)¶
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’
- get_stats(ports=None, sync_now=True, skip_zero=True, pid_input='_', is_sum=False)[source]¶
Gets all statistics on given ports, traffic and latency.
- Parameters
ports: list
sync_now: boolean
skip_zero: boolean
- pid_input: string
Input profile ID
- is_sum: boolean
Get total counter values
- clear_stats(ports=None, clear_global=True, clear_xstats=True, clear_traffic=True, pid_input='_')[source]¶
Clears statistics in given ports.
- Parameters
ports: list
clear_global: boolean
clear_xstats: boolean
clear_traffic: boolean
- pid_input: string
Input profile ID
- get_tg_names(pid_input='_')[source]¶
Returns a list of the names of all template groups defined in the current profile.
- Parameters
- pid_input: string
Input profile ID
- Raises
TRexError
- get_traffic_tg_stats(tg_names, skip_zero=True, pid_input='_')[source]¶
Returns the traffic statistics for the template groups specified in tg_names.
- Parameters
- tg_names: list or string
Contains the names of the template groups for which we want to get traffic statistics.
skip_zero: boolean
- pid_input: string
Input profile ID
- Raises
TRexErrorASTFErrorBadTGCan be thrown if tg_names is empty or contains a invalid name.
- get_traffic_stats(skip_zero=True, pid_input='_', is_sum=False)[source]¶
Returns aggregated traffic statistics.
- Parameters
skip_zero: boolean
- pid_input: string
Input profile ID
- is_sum: boolean
Get total counter values
- get_dynamic_traffic_stats(skip_zero=True, pid_input='_', is_sum=False)[source]¶
Gets the dynamic counters stats
- ::parameters:
skip_zero: boolean
- pid_input: string
Input profile ID
- is_sum: boolean
Get total counter values
- get_profiles_state()[source]¶
Gets an dictionary with the states of all the profiles.
- Returns
Dictionary containing profiles and their states. Keys are strings, pid (profile ID). Each profile can be in one of the following states: [‘STATE_IDLE’, ‘STATE_ASTF_LOADED’, ‘STATE_ASTF_PARSE’, ‘STATE_ASTF_BUILD’, ‘STATE_TX’, ‘STATE_ASTF_CLEANUP’, ‘STATE_ASTF_DELETE’, ‘STATE_UNKNOWN’].
- 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
- is_dynamic_traffic_stats_error(stats, pid_input='_', is_sum=False)[source]¶
Return Tuple if there is an error and what is the error (Bool,Errors)
- Parameters
stats: dict from get_dynamic_traffic_stats output from the same profile id and is_sum parameters
- pid_input: str
the profile id
- is_sum: boolean
if the stats are sum of all the profiles.
- clear_dynamic_traffic_stats(pid_input=None, clear_all=False)[source]¶
Clears dynamic traffic statistics.
- Parameters
- pid_input: string
Input profile ID
- clear_all: boolean
clear all the profiles sts
- clear_traffic_stats(pid_input='_', is_sum=False)[source]¶
Clears traffic statistics.
- Parameters
- pid_input: string
Input profile ID
- 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', port_ipv4_offset_s=None)[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)
- port_ipv4_offset_s: IP string
In case of different offset per side, the port_ipv4_offset_s should hold the server side offset. The default value is dual_ipv4
Note
VLAN will be taken from interface configuration
- raises
TRexError
- 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 objectSupported file formats:* JSON* YAML* Python
- tunables: dict
forward those key-value pairs to the topology Python file
- Raises
TRexError
- topo_save(filename)[source]¶
Save current topology to file
- Parameters
- filename: string
- Path to topology filename, supported formats:* JSON* YAML* Python
- tunnels_topo_load(topology, tunables={})[source]¶
Load network topology
- Parameters
- topology: string or TunnelTopo
- Path to topology filename or topology objectSupported file formats:* JSON* YAML* Python
- tunables: dict
forward those key-value pairs to the topology Python file
- Raises
TRexError
- is_tunnel_supported(tunnel_type=1)[source]¶
- parameters:
tunnel_type: currently only type 1 (gtpu) is supported
- ret:
- dict {is_tunnel_supported: true/false,
error_msg: why the tunnel is not supported}
- set_client_enable(client_list, is_enable)[source]¶
Version: 1 API to toggle state of client Input: List of clients and Action : state flag
- set_client_enable_range(client_start, client_end, is_enable)[source]¶
Version: 2 API to toggle state of client Input: Client range and Action : state flag
- get_clients_info(client_list, timeout=10)[source]¶
Version 1 API to get client information: Currently only state and if client is present. Input: List of clients
- get_clients_info_range(client_start, client_end, timeout=10)[source]¶
Version 2 API to get client information: Currently only state and if client is present. Input: Client range
- get_ignored_macs_ips(to_str=True)[source]¶
- getting the ignore MAC and IPv4 addresses from the server
- parameters
- to_str: Boolean
True: getting the addresses as str format. False: getting the addresses as numbers.
- set_ignored_macs_ips(mac_list=None, ip_list=None, is_str=True)[source]¶
- setting the ignore MAC and IPv4 addresses and push to the server
- parameters
- mac_list:
List that holds MAC addresses
- ip_list:
List that holds IPv4 addresses
- is_str: Boolean
boolean that indicates whether the MAC and IPv4 addresses are in str format.
- raises
TRexError
- service_line(line)[source]¶
Configures port for service mode. In service mode ports will reply to ARP, PING and etc. In ASTF, command will apply on all ports.
- add_profile(filename, ports=None, **kwargs)¶
- 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
- add_streams(streams, ports=None)¶
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
- 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_tpg_stats(port, tpgid, min_tag=0, max_tag=None, tag_list=None, unknown_tag=False, untagged=False)¶
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.
- clear_tpg_tx_stats(port, tpgid)¶
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
- clear_tpg_unknown_tags(port)¶
Clear Tagged Packet Group Unknown tags found in this port.
- Parameters
- port: uint8
Port on which we collect TPG packets.
- 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
- disable_tpg(username=None, surpress_log=False)¶
Disable Tagged Packet Grouping.
This method has 2 phases.
Disable TPG in DPs and Cp. Send a message to Rx to start deallocating.
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.
- 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
- enable_tpg(num_tpgids, tags, rx_ports=None)¶
Enable Tagged Packet Grouping.
This method has 3 phases:
Enable TPG in Control Plane and send message to Rx to allocate memory.
Wait until Rx finishes allocating.
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.
- 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_pgids()¶
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_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_pgid_stats(pgid_list=[])¶
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
Per flow statistics
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
Counters describing errors that occurred with this pg id
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
- 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_tpg_stats(port, tpgid, min_tag, max_tag, max_sections=50, unknown_tag=False, untagged=False)¶
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.
- get_tpg_status(username=None, port=None)¶
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.
- get_tpg_tags(min_tag=0, max_tag=None, username=None, port=None)¶
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_tx_stats(port, tpgid)¶
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}}}
- get_tpg_unknown_tags(port)¶
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} ]}
- 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
- pause(ports=None)¶
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_line(line)¶
Pause active traffic on specified ports on TRex
- pause_streams(port, stream_ids)¶
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
- 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_line(line)¶
Push a pcap file
- 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
- 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)¶
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
- 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)¶
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
- release_line(line)¶
Release ports
- remove_all_captures()¶
Removes any existing captures
- remove_all_streams(ports=None)¶
remove all streams from port(s)
- Parameters
- portslist
Ports on which to execute the command
- Raises
TRexError
- 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’
- remove_streams(stream_id_list, ports=None)¶
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
- 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
- resume(ports=None)¶
Resume traffic on port(s)
- Parameters
- portslist
Ports on which to execute the command
- Raises
TRexError
- resume_line(line)¶
Resume active traffic on specified ports on TRex
- resume_streams(port, stream_ids)¶
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
- scan6(ports=None, timeout=3, verbose=False)¶
Search for IPv6 devices on ports
- Parameters
- ports: list
List of port IDs at which ports to run scan6
- timeout: float
how much time to wait for responses
- verbose: bool
log for each request the response
- Returns
list of dictionaries per neighbor:
type - type of device: ‘Router’ or ‘Host’
mac - MAC address of device
ipv6 - IPv6 address of device
- Raises
:exe:’TRexError’
- scan6_line(line)¶
Search for IPv6 neighbors
- server_shutdown(force=False)¶
Sends the server a request for total shutdown
- Parameters
- force: bool
Shutdown server even if some ports are owned by another user
- Raises
TRexError
- set_bird_node(node_port, mac, ipv4=None, ipv4_subnet=None, ipv6_enabled=None, ipv6=None, ipv6_subnet=None, vlans=None, tpids=None, mtu=None)¶
a utility function that works on top of
set_namespace_start()andwait_for_async_results()batch operation API. the function creates a “bird node” using veth’s in bird namespace in trex.usage example:
c.set_bird_node(node_port = 0, mac = "00:00:00:01:00:06", ipv4 = "1.1.1.3", ipv4_subnet = 24, ipv6_enabled = True, ipv6_subnet = 124, vlans = [22], tpids = [0x8100])
- Parameters
- node_port: int
Port id to set the bird node on
- mac: string
Mac address for the new bird node in format xx:xx:xx:xx:xx:xx
- ipv4: string
Ipv4 address for the new bird node
- ipv4_subnet: int
Ipv4 subnet for the new bird node
- ipv6_enabled: bool
True/False if ipv6 enabled on the new node, mandatory for ipv6 config
- ipv6: string
Ipv6 address for the new bird node
- ipv6_subnet: int
Ipv6 subnet for the new bird node
- vlans: list
Array of up to 2 uint16 tags.
- tpids: list
Array of tpidss that correspond to vlans. Default is [0x8100] in case of single VLAN and [0x88a8, 0x8100] in case of QinQ.
- mtu: int
MTU for bird node.
- Raises
TRexErrorin case of any error
- set_capture_port_bpf_filter(port, bpf_filter)¶
Set the BPF filter for the capture port
- Parameters
- port: int
The port to change the filter of the capture port
- bpf_filter: string
The new BPF filter (empty disables the filter)
- Raises
TRexError
- set_global_cfg(params)¶
Change global configuration parameters.
- Parameters
- params: dictionary
- dictionary of global configuration parameters. Available parameters:sched_max_stretch: doubleThe 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: boolEnable 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: boolEnable 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()andwait_for_async_results()batch operation API. it creates a batch of one command and one result. It is good for slow operations that require blocking (such as get API)the function calls:
c.set_namespace_start(Obj(method, args)) r=c.wait_for_async_results() return (r)
usage example:
r=set_namespace(port=0,method='get_nodes')
- Parameters
- port: int
Port ID to set the dest address
- method: string
method name. see NSCmds object for method names
- args: dict
method args
- Raises
TRexErrorin case of any error
- set_namespace_start(port, ns_cmds)¶
Start namespace batch operation. This commands is a batch command that interact with the kernel and could be slow in case of a big batch. use wait_for_async_results to block for the response, or is_async_results_ready to pool if the results is ready. see see
trex.common.trex_ns.NSCmdsandtrex.common.trex_ns.NSCmdResultUsing other Python API while there is an active batch is not recommended:
c.set_namespace_start(port=0, ns_cmds) res = c.wait_for_async_results(port=0);
- Parameters
- port: int
Port ID to set the dest address
ns_cmds : see
trex.common.trex_ns.NSCmdsobjects that includes batch 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 VXLANUDP(<dst_port>)/VXLAN()/Ether()/… <— NIC will look for flow stats magic hereLimited only to supported NICs (currently i40e)
- Raises
:exe:’TRexError’
- set_port_attr_line(line)¶
Sets port attributes
- set_rx_queue(ports=None, size=1000)¶
Sets RX queue for port(s) The queue is cyclic and will hold last ‘size’ packets
- Parameters
- ports: list
For which ports to apply a queue
- size: int
size of the queue
- Raises
:exe:’TRexError’
- set_service_mode_base(ports=None, enabled=True, filtered=False, mask=None)¶
Set service mode for port(s) In service mode ports will respond to ARP, PING and etc. “enable” and “filtered” are mutual exclusive, choose 1 of them or none
- Parameters
- ports: list
For which ports to configure service mode on/off
- enabled: bool
True for activating service mode, False for disabling. Mutual exclusive with “filtered”
- filtered: bool
True for activating service filtered mode, False for disabling. Mutual exclusive with “enabled”
- mask: int
Mask to apply on each port in ports while filtered mode is on. Only packets that are correspond to the port mask will be transferred. Masks flags: NO_MASK = 0 NO_TCP_UDP_MASK = 1 BGP_MASK = 2 DHCP_MASK = 4 TRANSPORT = 8 MDNS = 16 ALL_MASK = 255
- Raises
:exe:’TRexError’
- set_timeout(timeout_sec)¶
Set timeout for connectivity to TRex server. Must be not connected.
- Parameters
- timeout_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_stats(line)¶
Show Tagged Packet Group Statistics
- show_tpg_status(line)¶
Show Tagged Packet Group Status
- show_tpg_tags(line)¶
Show Tagged Packet Group Tags
- show_tpg_tx_stats(line)¶
Show Tagged Packet Group Tx Statistics
- show_tpg_unknown_stats(line)¶
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
- 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_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
- 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
- streams_line(line)¶
Get loaded to server streams information
- tpg_clear_stats(line)¶
Clear Tagged Packet Group Stats
- tpg_clear_tx_stats(line)¶
Clear Tagged Packet Group Tx Stats
- tpg_clear_unknown_stats(line)¶
Clear Tagged Packet Group Unknown Tags
- tpg_disable(line)¶
Disable Tagged Packet Group
- tpg_enable(line)¶
Enable Tagged Packet Group
- tpg_update(line)¶
Update Tagged Packet Group Tag
- 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)¶
- 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
- update_tpg_tags(new_tags, clear=False)¶
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.
- wait_for_async_results(port, timeout=None, cb=None)¶
wait for the namespace batch operations to finish, return an a list of batch results it includes something like that [None, {‘u’error’:’some error’},{u’result’: {u’nodes’: [u’’]}}
None : means that there is no error and command was executed object: that include ‘error’ means that there is an error object with ‘result’
- Parameters
- port: int
Port ID to set the dest address
timeout : in second, None is unlimited
cb: A callback function that gets an object for calculating progress of a log operation
exec_cmds: total commands executed total_cmds: total commands in the queue errs_cmds: number of errors in the last operation ticket_id: ticket id
this will print the progress into the screen:
def progress_cb(obj): prog = 100.0*( float(obj['exec_cmds']) / float(obj['total_cmds'])) err = obj['errs_cmds'] print("progress {:3.0f}% errors : {}".format(prog,err))
- Raises
TRexErrorin case of any error
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()
# Example: tempate group name and counters
self.c.load_profile(profile)
self.c.clear_stats()
self.c.start(duration = 60, mult = 100)
self.c.wait_on_traffic()
names = self.c.get_tg_names()
stats = self.c.get_traffic_tg_stats(names[:2])