diff options
Diffstat (limited to 'scripts/automation/trex_control_plane/examples')
9 files changed, 834 insertions, 0 deletions
diff --git a/scripts/automation/trex_control_plane/examples/__init__.py b/scripts/automation/trex_control_plane/examples/__init__.py new file mode 100755 index 00000000..d3f5a12f --- /dev/null +++ b/scripts/automation/trex_control_plane/examples/__init__.py @@ -0,0 +1 @@ +
diff --git a/scripts/automation/trex_control_plane/examples/client_interactive_example.py b/scripts/automation/trex_control_plane/examples/client_interactive_example.py new file mode 100755 index 00000000..d21b2b15 --- /dev/null +++ b/scripts/automation/trex_control_plane/examples/client_interactive_example.py @@ -0,0 +1,254 @@ +#!/router/bin/python-2.7.4 + +import trex_root_path +from client.trex_client import * +from common.trex_exceptions import * +import cmd +import termstyle +import os +from argparse import ArgumentParser +from pprint import pprint +import json +import time +import socket +import errno + +class InteractiveTRexClient(cmd.Cmd): + + intro = termstyle.green("\nInteractive shell to play with Cisco's TRex API.\nType help to view available pre-defined scenarios\n(c) All rights reserved.\n") + prompt = '> ' + + def __init__(self, trex_host, max_history_size = 100, trex_port = 8090, verbose_mode = False ): + cmd.Cmd.__init__(self) + self.verbose = verbose_mode + self.trex = CTRexClient(trex_host, max_history_size, trex_daemon_port = trex_port, verbose = verbose_mode) + self.DEFAULT_RUN_PARAMS = dict( m = 1.5, + nc = True, + p = True, + d = 100, + f = 'avl/sfr_delay_10_1g.yaml', + l = 1000) + self.run_params = dict(self.DEFAULT_RUN_PARAMS) + self.decoder = json.JSONDecoder() + + + def do_push_files (self, filepaths): + """Pushes a custom file to be stored locally on TRex server.\nPush multiple files by spefiying their path separated by ' ' (space).""" + try: + filepaths = filepaths.split(' ') + print termstyle.green("*** Starting pushing files ({trex_files}) to TRex. ***".format (trex_files = ', '.join(filepaths)) ) + ret_val = self.trex.push_files(filepaths) + if ret_val: + print termstyle.green("*** End of TRex push_files method (success) ***") + else: + print termstyle.magenta("*** End of TRex push_files method (failed) ***") + + except IOError as inst: + print termstyle.magenta(inst) + + def do_show_default_run_params(self,line): + """Outputs the default TRex running parameters""" + pprint(self.DEFAULT_RUN_PARAMS) + print termstyle.green("*** End of default TRex running parameters ***") + + def do_show_run_params(self,line): + """Outputs the currently configured TRex running parameters""" + pprint(self.run_params) + print termstyle.green("*** End of TRex running parameters ***") + + def do_update_run_params(self, json_str): + """Updates provided parameters on TRex running configuration. Provide using JSON string""" + if json_str: + try: + upd_params = self.decoder.decode(json_str) + self.run_params.update(upd_params) + print termstyle.green("*** End of TRex parameters update ***") + except ValueError as inst: + print termstyle.magenta("Provided illegal JSON string. Please try again.\n[", inst,"]") + else: + print termstyle.magenta("JSON configuration string is missing. Please try again.") + + def do_show_status (self, line): + """Prompts TRex current status""" + print self.trex.get_running_status() + print termstyle.green("*** End of TRex status prompt ***") + + def do_show_trex_files_path (self, line): + """Prompts the local path in which files are stored when pushed to trex server from client""" + print self.trex.get_trex_files_path() + print termstyle.green("*** End of trex_files_path prompt ***") + + def do_show_reservation_status (self, line): + """Prompts if TRex is currently reserved or not""" + if self.trex.is_reserved(): + print "TRex is reserved" + else: + print "TRex is NOT reserved" + print termstyle.green("*** End of reservation status prompt ***") + + def do_reserve_trex (self, user): + """Reserves the usage of TRex to a certain user""" + try: + if not user: + ret = self.trex.reserve_trex() + else: + ret = self.trex.reserve_trex(user.split(' ')[0]) + print termstyle.green("*** TRex reserved successfully ***") + except TRexException as inst: + print termstyle.red(inst) + + def do_cancel_reservation (self, user): + """Cancels a current reservation of TRex to a certain user""" + try: + if not user: + ret = self.trex.cancel_reservation() + else: + ret = self.trex.cancel_reservation(user.split(' ')[0]) + print termstyle.green("*** TRex reservation canceled successfully ***") + except TRexException as inst: + print termstyle.red(inst) + + def do_restore_run_default (self, line): + """Restores original TRex running configuration""" + self.run_params = dict(self.DEFAULT_RUN_PARAMS) + print termstyle.green("*** End of restoring default run parameters ***") + + def do_run_until_finish (self, sample_rate): + """Starts TRex and sample server until run is done.""" + print termstyle.green("*** Starting TRex run_until_finish scenario ***") + + if not sample_rate: # use default sample rate if not passed + sample_rate = 5 + try: + sample_rate = int(sample_rate) + ret = self.trex.start_trex(**self.run_params) + self.trex.sample_to_run_finish(sample_rate) + print termstyle.green("*** End of TRex run ***") + except ValueError as inst: + print termstyle.magenta("Provided illegal sample rate value. Please try again.\n[", inst,"]") + except TRexException as inst: + print termstyle.red(inst) + + def do_run_and_poll (self, sample_rate): + """Starts TRex and sample server manually until run is done.""" + print termstyle.green("*** Starting TRex run and manually poll scenario ***") + if not sample_rate: # use default sample rate if not passed + sample_rate = 5 + try: + sample_rate = int(sample_rate) + ret = self.trex.start_trex(**self.run_params) + last_res = dict() + while self.trex.is_running(dump_out = last_res): + obj = self.trex.get_result_obj() + if (self.verbose): + print obj + # do WHATEVER here + time.sleep(sample_rate) + + print termstyle.green("*** End of TRex run ***") + except ValueError as inst: + print termstyle.magenta("Provided illegal sample rate value. Please try again.\n[", inst,"]") + except TRexException as inst: + print termstyle.red(inst) + + + def do_run_until_condition (self, sample_rate): + """Starts TRex and sample server until condition is satisfied.""" + print termstyle.green("*** Starting TRex run until condition is satisfied scenario ***") + + def condition (result_obj): + return result_obj.get_current_tx_rate()['m_tx_pps'] > 200000 + + if not sample_rate: # use default sample rate if not passed + sample_rate = 5 + try: + sample_rate = int(sample_rate) + ret = self.trex.start_trex(**self.run_params) + ret_val = self.trex.sample_until_condition(condition, sample_rate) + print ret_val + print termstyle.green("*** End of TRex run ***") + except ValueError as inst: + print termstyle.magenta("Provided illegal sample rate value. Please try again.\n[", inst,"]") + except TRexException as inst: + print termstyle.red(inst) + + def do_start_and_return (self, line): + """Start TRex run and once in 'Running' mode, return to cmd prompt""" + print termstyle.green("*** Starting TRex run, wait until in 'Running' state ***") + try: + ret = self.trex.start_trex(**self.run_params) + print termstyle.green("*** End of scenario (TRex is probably still running!) ***") + except TRexException as inst: + print termstyle.red(inst) + + def do_poll_once (self, line): + """Performs a single poll of TRex current data dump (if TRex is running) and prompts and short version of latest result_obj""" + print termstyle.green("*** Trying TRex single poll ***") + try: + last_res = dict() + if self.trex.is_running(dump_out = last_res): + obj = self.trex.get_result_obj() + print obj + else: + print termstyle.magenta("TRex isn't currently running.") + print termstyle.green("*** End of scenario (TRex is posssibly still running!) ***") + except TRexException as inst: + print termstyle.red(inst) + + + def do_stop_trex (self, line): + """Try to stop TRex run (if TRex is currently running)""" + print termstyle.green("*** Starting TRex termination ***") + try: + ret = self.trex.stop_trex() + print termstyle.green("*** End of scenario (TRex is not running now) ***") + except TRexException as inst: + print termstyle.red(inst) + + def do_kill_indiscriminately (self, line): + """Force killing of running TRex process (if exists) on the server.""" + print termstyle.green("*** Starting TRex termination ***") + ret = self.trex.force_kill() + if ret: + print termstyle.green("*** End of scenario (TRex is not running now) ***") + elif ret is None: + print termstyle.magenta("*** End of scenario (TRex termination aborted) ***") + else: + print termstyle.red("*** End of scenario (TRex termination failed) ***") + + def do_exit(self, arg): + """Quits the application""" + print termstyle.cyan('Bye Bye!') + return True + + +if __name__ == "__main__": + parser = ArgumentParser(description = termstyle.cyan('Run TRex client API demos and scenarios.'), + usage = """client_interactive_example [options]""" ) + + parser.add_argument('-v', '--version', action='version', version='%(prog)s 1.0 \t (C) Cisco Systems Inc.\n') + + parser.add_argument("-t", "--trex-host", required = True, dest="trex_host", + action="store", help="Specify the hostname or ip to connect with TRex server.", + metavar="HOST" ) + parser.add_argument("-p", "--trex-port", type=int, default = 8090, metavar="PORT", dest="trex_port", + help="Select port on which the TRex server listens. Default port is 8090.", action="store") + parser.add_argument("-m", "--maxhist", type=int, default = 100, metavar="SIZE", dest="hist_size", + help="Specify maximum history size saved at client side. Default size is 100.", action="store") + parser.add_argument("--verbose", dest="verbose", + action="store_true", help="Switch ON verbose option at TRex client. Default is: OFF.", + default = False ) + args = parser.parse_args() + + try: + InteractiveTRexClient(args.trex_host, args.hist_size, args.trex_port, args.verbose).cmdloop() + + except KeyboardInterrupt: + print termstyle.cyan('Bye Bye!') + exit(-1) + except socket.error, e: + if e.errno == errno.ECONNREFUSED: + raise socket.error(errno.ECONNREFUSED, "Connection from TRex server was terminated. Please make sure the server is up.") + + + diff --git a/scripts/automation/trex_control_plane/examples/client_tcl_example.tcl b/scripts/automation/trex_control_plane/examples/client_tcl_example.tcl new file mode 100755 index 00000000..3467c898 --- /dev/null +++ b/scripts/automation/trex_control_plane/examples/client_tcl_example.tcl @@ -0,0 +1,28 @@ +#!/bin/sh +#\ +exec /usr/bin/expect "$0" "$@" +# + +# Sourcing the tcl trex client api +source trex_tcl_client.tcl + +#Initializing trex server attributes +set check [TRexTclClient::create_host "localhost"] + +#Formulate the command options as a dict +set trex_cmds [dict create c 2 m 10 l 1000 ] + +#call the start_trex rpc function by feeding the appropriate arguments +set status [::TRexTclClient::start_trex "cap2/dns.yaml" 40 $trex_cmds] +puts "Status : $status" + +#get the result json +set result [::TRexTclClient::get_result_obj] +puts "$result" + +#stop the trex server +set ret_value [ ::TRexTclClient::stop_trex $status] +puts "Stop value : $ret_value" +puts "\n \n" + + diff --git a/scripts/automation/trex_control_plane/examples/interactive_stateless.py b/scripts/automation/trex_control_plane/examples/interactive_stateless.py new file mode 100644 index 00000000..f6ada17d --- /dev/null +++ b/scripts/automation/trex_control_plane/examples/interactive_stateless.py @@ -0,0 +1,128 @@ +#!/router/bin/python + +import trex_root_path +from client.trex_stateless_client import * +from common.trex_exceptions import * +import cmd +from termstyle import termstyle +# import termstyle +import os +from argparse import ArgumentParser +import socket +import errno +import ast +import json + + +class InteractiveStatelessTRex(cmd.Cmd): + + intro = termstyle.green("\nInteractive shell to play with Cisco's TRex stateless API.\ + \nType help to view available pre-defined scenarios\n(c) All rights reserved.\n") + prompt = '> ' + + def __init__(self, trex_host, trex_port, virtual, verbose): + cmd.Cmd.__init__(self) + + self.verbose = verbose + self.virtual = virtual + self.trex = STLClient(trex_host, trex_port, self.virtual) + self.DEFAULT_RUN_PARAMS = dict(m=1.5, + nc=True, + p=True, + d=100, + f='avl/sfr_delay_10_1g.yaml', + l=1000) + self.run_params = dict(self.DEFAULT_RUN_PARAMS) + + def do_transmit(self, line): + """Transmits a request over using a given link to server.\ + \nuse: transmit [method_name] [method_params]""" + if line == "": + print "\nUsage: [method name] [param dict as string]\n" + print "Example: rpc test_add {'x': 12, 'y': 17}\n" + return + + args = line.split(' ', 1) # args will have max length of 2 + method_name = args[0] + params = None + bad_parse = False + + try: + params = ast.literal_eval(args[1]) + if not isinstance(params, dict): + bad_parse = True + except ValueError as e1: + bad_parse = True + except SyntaxError as e2: + bad_parse = True + + if bad_parse: + print "\nValue should be a valid dict: '{0}'".format(args[1]) + print "\nUsage: [method name] [param dict as string]\n" + print "Example: rpc test_add {'x': 12, 'y': 17}\n" + return + + response = self.trex.transmit(method_name, params) + if not self.virtual: + # expect response + rc, msg = response + if rc: + print "\nServer Response:\n\n" + json.dumps(msg) + "\n" + else: + print "\n*** " + msg + "\n" + + + + + + def do_push_files(self, filepaths): + """Pushes a custom file to be stored locally on TRex server.\ + \nPush multiple files by specifying their path separated by ' ' (space).""" + try: + filepaths = filepaths.split(' ') + print termstyle.green("*** Starting pushing files ({trex_files}) to TRex. ***".format( + trex_files=', '.join(filepaths)) + ) + ret_val = self.trex.push_files(filepaths) + if ret_val: + print termstyle.green("*** End of TRex push_files method (success) ***") + else: + print termstyle.magenta("*** End of TRex push_files method (failed) ***") + + except IOError as inst: + print termstyle.magenta(inst) + +if __name__ == "__main__": + parser = ArgumentParser(description=termstyle.cyan('Run TRex client stateless API demos and scenarios.'), + usage="client_interactive_example [options]") + + parser.add_argument('-v', '--version', action='version', version='%(prog)s 1.0 \t (C) Cisco Systems Inc.\n') + + parser.add_argument("-t", "--trex-host", required = True, dest="trex_host", + action="store", help="Specify the hostname or ip to connect with TRex server.", + metavar="HOST" ) + parser.add_argument("-p", "--trex-port", type=int, default = 5050, metavar="PORT", dest="trex_port", + help="Select port on which the TRex server listens. Default port is 5050.", action="store") + # parser.add_argument("-m", "--maxhist", type=int, default = 100, metavar="SIZE", dest="hist_size", + # help="Specify maximum history size saved at client side. Default size is 100.", action="store") + parser.add_argument("--virtual", dest="virtual", + action="store_true", + help="Switch ON virtual option at TRex client. Default is: OFF.", + default=False) + parser.add_argument("--verbose", dest="verbose", + action="store_true", + help="Switch ON verbose option at TRex client. Default is: OFF.", + default=False) + args = parser.parse_args() + + try: + InteractiveStatelessTRex(**vars(args)).cmdloop() + + except KeyboardInterrupt: + print termstyle.cyan('Bye Bye!') + exit(-1) + except socket.error, e: + if e.errno == errno.ECONNREFUSED: + raise socket.error(errno.ECONNREFUSED, + "Connection from TRex server was terminated. \ + Please make sure the server is up.") diff --git a/scripts/automation/trex_control_plane/examples/pkt_generation_for_trex.py b/scripts/automation/trex_control_plane/examples/pkt_generation_for_trex.py new file mode 100755 index 00000000..acaa95d3 --- /dev/null +++ b/scripts/automation/trex_control_plane/examples/pkt_generation_for_trex.py @@ -0,0 +1,105 @@ +#!/router/bin/python + +###################################################################################### +### ### +### TRex end-to-end demo script, written by TRex dev-team ### +### THIS SCRIPT ASSUMES PyYaml and Scapy INSTALLED ON PYTHON'S RUNNING MACHINE ### +### (for any question please contact trex-dev team @ trex-dev@cisco.com) ### +### ### +###################################################################################### + + +import logging +import time +import trex_root_path +from client.trex_client import * +from client_utils.general_utils import * +from client_utils.trex_yaml_gen import * +from pprint import pprint +from argparse import ArgumentParser + +# import scapy package +logging.getLogger("scapy.runtime").setLevel(logging.ERROR) # supress scapy import warnings from being displayed +from scapy.all import * + + +def generate_dns_packets (src_ip, dst_ip): + dns_rqst = Ether(src='00:15:17:a7:75:a3', dst='e0:5f:b9:69:e9:22')/IP(src=src_ip,dst=dst_ip,version=4L)/UDP(dport=53, sport=1030)/DNS(rd=1,qd=DNSQR(qname="www.cisco.com")) + dns_resp = Ether(src='e0:5f:b9:69:e9:22', dst='00:15:17:a7:75:a3')/IP(src=dst_ip,dst=src_ip,version=4L)/UDP(dport=1030, sport=53)/DNS(aa=1L, qr=1L, an=DNSRR(rclass=1, rrname='www.cisco.com.', rdata='100.100.100.100', type=1), ad=0L, qdcount=1, ns=None, tc=0L, rd=0L, ar=None, opcode=0L, ra=1L, cd=0L, z=0L, rcode=0L, qd=DNSQR(qclass=1, qtype=1, qname='www.cisco.com.')) + return [dns_rqst, dns_resp] + +def pkts_to_pcap (pcap_filename, packets): + wrpcap(pcap_filename, packets) + + +def main (args): + # instantiate TRex client + trex = CTRexClient('trex-dan', verbose = args.verbose) + + if args.steps: + print "\nNext step: .pcap generation." + raw_input("Press Enter to continue...") + # generate TRex traffic. + pkts = generate_dns_packets('21.0.0.2', '22.0.0.12') # In this case - DNS traffic (request-response) + print "\ngenerated traffic:" + print "==================" + map(lambda x: pprint(x.summary()) , pkts) + pkts_to_pcap("dns_traffic.pcap", pkts) # Export the generated to a .pcap file + + if args.steps: + print "\nNext step: .yaml generation." + raw_input("Press Enter to continue...") + # Generate .yaml file that uses the generated .pcap file + trex_files_path = trex.get_trex_files_path() # fetch the path in which packets are saved on TRex server + yaml_obj = CTRexYaml(trex_files_path) # instantiate CTRexYaml obj + + # set .yaml file parameters according to need and use + ret_idx = yaml_obj.add_pcap_file("dns_traffic.pcap") + yaml_obj.set_cap_info_param('cps', 1.1, ret_idx) + + # export yaml_ob to .yaml file + yaml_file_path = trex_files_path + 'dns_traffic.yaml' + yaml_obj.to_yaml('dns_traffic.yaml') + print "\ngenerated .yaml file:" + print "====================" + yaml_obj.dump() + + if args.steps: + print "\nNext step: run TRex with provided files." + raw_input("Press Enter to continue...") + # push all relevant files to server + trex.push_files( yaml_obj.get_file_list() ) + + print "\nStarting TRex..." + trex.start_trex(c = 2, + m = 1.5, + nc = True, + p = True, + d = 30, + f = yaml_file_path, # <-- we use out generated .yaml file here + l = 1000) + + if args.verbose: + print "TRex state changed to 'Running'." + print "Sampling TRex in 0.2 samples/sec (single sample every 5 secs)" + + last_res = dict() + while trex.is_running(dump_out = last_res): + print "CURRENT RESULT OBJECT:" + obj = trex.get_result_obj() + print obj + time.sleep(5) + + +if __name__ == "__main__": + parser = ArgumentParser(description = 'Run TRex client API end-to-end example.', + usage = """pkt_generation_for_trex [options]""" ) + + parser.add_argument("-s", "--step-by-step", dest="steps", + action="store_false", help="Switch OFF step-by-step script overview. Default is: ON.", + default = True ) + parser.add_argument("--verbose", dest="verbose", + action="store_true", help="Switch ON verbose option at TRex client. Default is: OFF.", + default = False ) + args = parser.parse_args() + main(args)
\ No newline at end of file diff --git a/scripts/automation/trex_control_plane/examples/stateless_example.py b/scripts/automation/trex_control_plane/examples/stateless_example.py new file mode 100755 index 00000000..bb0fe983 --- /dev/null +++ b/scripts/automation/trex_control_plane/examples/stateless_example.py @@ -0,0 +1,30 @@ +#!/router/bin/python + +import trex_root_path +from client.trex_hltapi import CTRexHltApi + +if __name__ == "__main__": + port_list = [1,2] + try: + hlt_client = CTRexHltApi() + con = hlt_client.connect("localhost", port_list, "danklei", break_locks=True, reset=True)#, port=6666) + print con + + res = hlt_client.traffic_config("create", 1)#, ip_src_addr="2000.2.2") + print res + res = hlt_client.traffic_config("create", 2)#, ip_src_addr="2000.2.2") + print res + + res = hlt_client.traffic_control("run", [1, 2])#, ip_src_addr="2000.2.2") + print res + + res = hlt_client.traffic_control("stop", [1, 2])#, ip_src_addr="2000.2.2") + print res + + + + except Exception as e: + raise + finally: + res = hlt_client.cleanup_session(port_list) + print res
\ No newline at end of file diff --git a/scripts/automation/trex_control_plane/examples/trex_root_path.py b/scripts/automation/trex_control_plane/examples/trex_root_path.py new file mode 100755 index 00000000..3aefd1d2 --- /dev/null +++ b/scripts/automation/trex_control_plane/examples/trex_root_path.py @@ -0,0 +1,15 @@ +#!/router/bin/python
+
+import os
+import sys
+
+def add_root_to_path ():
+ """adds trex_control_plane root dir to script path, up to `depth` parent dirs"""
+ root_dirname = 'trex_control_plane'
+ file_path = os.path.dirname(os.path.realpath(__file__))
+
+ components = file_path.split(os.sep)
+ sys.path.append( str.join(os.sep, components[:components.index(root_dirname)+1]) )
+ return
+
+add_root_to_path()
diff --git a/scripts/automation/trex_control_plane/examples/trex_tcl_client.tcl b/scripts/automation/trex_control_plane/examples/trex_tcl_client.tcl new file mode 100755 index 00000000..f700a5d2 --- /dev/null +++ b/scripts/automation/trex_control_plane/examples/trex_tcl_client.tcl @@ -0,0 +1,228 @@ +#!/bin/sh +#\ +exec /usr/bin/expect "$0" "$@" +# + +package require JSONRPC +package require json + + + +################################################################ +# Author: Vamsi Kalapala +# Version: 0.1 +# Description: This Trex Tcl Client will help in conecting to the trex_host +# by sending JSOMN RPC calls to the python trex server. +# +# +# +################################################################ + +namespace eval TRexTclClient { + variable version 0.1 + ################################################################ + # trex_host should be either the IPV4 address or + # dns name accompanied by http:// + # Accepted trex_host names: + # http://172.18.73.122, + # http://up-trex-1-10g + # http://up-trex-1-10g.cisco.com, + ################################################################ + + variable TRex_Status [dict create 1 "Idle" 2 "Starting" 3 "Running"] + + variable trex_host "localhost" + variable server_port "8090" + variable trex_zmq_port "4500" + + variable current_seq_num 0 + + variable trex_debug 0 + +} + + +proc TRexTclClient::create_host {trex_host {server_port 8090} {trex_zmq_port 4500} {trex_debug 0}} { + puts "\n" + + if (![string match "http://*" $trex_host]) { + append temp_host "http://" $trex_host + set trex_host $temp_host + #puts $trex_host + #puts stderr "The trex_host should contain http:// in it" + #exit 1 + } + + set ::TRexTclClient::trex_host $trex_host + if ($TRexTclClient::trex_debug) { + puts "The server port is : $server_port" + } + set TRexTclClient::server_port $server_port + set TRexTclClient::trex_zmq_port $trex_zmq_port + set TRexTclClient::trex_debug $trex_debug + + set trex_host_url [TRexTclClient::appendHostName] + puts "Host attributes have been initialized." + puts "Establishing connection to server at $trex_host_url ..." + puts "\n" + return 1 +} + +proc TRexTclClient::appendHostName {} { + ################################################################ + # Please check for the need of more args here. + # + # ** Do sanity checks ** + ################################################################ + if {[string is integer $TRexTclClient::server_port] && $TRexTclClient::server_port < 65535 } { + return [append newHost $TRexTclClient::trex_host ":" $TRexTclClient::server_port] + } else { + puts stderr "\[ERROR\]: Invalid server port. Valid server port range is 0 - 65535 !" + puts "\nExiting client initialization ... \n" + exit 1 + } +} + +# ** Chnage the args list to keyed lists or dictionaries** +proc TRexTclClient::start_trex {f d trex_cmd_options {user "root"} {block_to_success True} {timeout 40}} { + + ################################################################ + # This proc sends out the RPC call to start trex. + # 'f' should string + # 'd' should be integer and greater than 30 + # 'trex_cmd_options' SHOULD be a dict + # + ################################################################ + + set trex_host_url [TRexTclClient::appendHostName] + if {$d<30} { + puts stderr "\[ERROR\]: The test duration should be at least 30 secs." + puts "\nExiting start_trex process ... \n" + exit 1 + } + + if ($TRexTclClient::trex_debug) { + puts "\[start_trex :: before call\] : The arguements are: " + puts "URL: $trex_host_url" + puts "f: $f" + puts "d: $d" + puts "trex_cmd_options: $trex_cmd_options" + puts "user: $user" + puts "block_to_success: $block_to_success" + puts "timeout: $timeout\n" + } + + JSONRPC::create start_trex -proxy $trex_host_url -params {"trex_cmd_options" "object" "user" "string" "block_to_success" "string" "timeout" "int"} + puts "Connecting to Trex host at $trex_host_url ....." + + dict append trex_cmd_options d $d + dict append trex_cmd_options f $f + if ($TRexTclClient::trex_debug) { + puts "\[start_trex :: before call\] : trex_cmd_options: $trex_cmd_options \n" + } + set ret_value [ start_trex $trex_cmd_options $user $block_to_success $timeout] + + if ($TRexTclClient::trex_debug) { + puts "\[start_trex :: after call\] : The returned result: $ret_value" + } + + if ($ret_value!=0) { + puts "Connection successful! \n" + puts "TRex started running successfully! \n" + puts "Trex Run Sequence number: $ret_value" + set TRexTclClient::current_seq_num $ret_value + return $ret_value + } + + puts "\n \n" + return 0 +} + +proc TRexTclClient::stop_trex {seq} { + set trex_host_url [TRexTclClient::appendHostName] + JSONRPC::create stop_trex -proxy $trex_host_url -params {seq int} + set ret_value [ stop_trex $TRexTclClient::current_seq_num] + if ($ret_value) { + puts "TRex Run successfully stopped!" + } else { + puts "Unable to stop the server. Either provided sequence number is incorrect or you dont have sufficient permissions!" + } + puts "\n" + return $ret_value +} + +proc TRexTclClient::get_trex_files_path {} { + + set trex_host_url [TRexTclClient::appendHostName] + JSONRPC::create get_files_path -proxy $trex_host_url + set ret_value [get_files_path] + puts "The Trex file path is $ret_value" + puts "\n" + return $ret_value +} + +proc TRexTclClient::get_running_status {} { + + set trex_host_url [TRexTclClient::appendHostName] + JSONRPC::create get_running_status -proxy $trex_host_url + set ret_value [get_running_status] + if ($TRexTclClient::trex_debug) { + puts "\[get_running_status :: after call\] : The result is: $ret_value" + } + set current_status [dict get $TRexTclClient::TRex_Status [dict get $ret_value "state" ]] + set current_status_decr [dict get $ret_value "verbose"] + puts "Current TRex Status: $current_status" + puts "TRex Status Verbose: $current_status_decr" + puts "\n" + return $ret_value +} + +proc TRexTclClient::get_result_obj { {copy_obj True} } { + + set trex_host_url [TRexTclClient::appendHostName] + JSONRPC::create get_running_info -proxy $trex_host_url + + set result_json_obj [get_running_info ] + set result_dict_obj [json::json2dict $result_json_obj] + if ($TRexTclClient::trex_debug) { + puts "\[get_result_obj :: after call\] : The result json is: " + puts "################################################################" + puts "$result_json_obj" + puts "################################################################" + puts "\[get_result_obj :: after call\] : The result dict is: " + puts "################################################################" + puts "$result_dict_obj" + puts "################################################################" + } + puts "\n" + return $result_dict_obj +} + +proc TRexTclClient::is_reserved {} { + set trex_host_url [TRexTclClient::appendHostName] + JSONRPC::create is_reserved -proxy $trex_host_url + puts "\n" + set ret_value [is_reserved] + if ($TRexTclClient::trex_debug) { + puts "\[is_reserved :: after call\] : The result json is: $ret_value" + } + return $ret_value +} + +proc TRexTclClient::get_trex_version {} { + set trex_host_url [TRexTclClient::appendHostName] + JSONRPC::create get_trex_version -proxy $trex_host_url + set ret_value [get_trex_version] + puts "\n" + return $ret_value +} + + + + + +################################################################ +# +# +# +################################################################ diff --git a/scripts/automation/trex_control_plane/examples/zmq_server_client.py b/scripts/automation/trex_control_plane/examples/zmq_server_client.py new file mode 100755 index 00000000..15f37f1a --- /dev/null +++ b/scripts/automation/trex_control_plane/examples/zmq_server_client.py @@ -0,0 +1,45 @@ +import sys
+import os
+python2_zmq_path = os.path.abspath(os.path.join(os.pardir,os.pardir,os.pardir,
+ 'external_libs','pyzmq-14.5.0','python2','fedora18','64bit'))
+sys.path.append(python2_zmq_path)
+import zmq
+import json
+from argparse import *
+
+parser = ArgumentParser(description=' Runs a Scapy Server Client example ')
+parser.add_argument('-p','--dest-scapy-port',type=int, default = 4507, dest='dest_scapy_port',
+ help='Select port to which this Scapy Server client will send to.\n default is 4507\n',action='store')
+parser.add_argument('-s','--server',type=str, default = 'localhost', dest='dest_scapy_ip',
+ help='Remote server IP address .\n default is localhost\n',action='store')
+
+args = parser.parse_args()
+
+dest_scapy_port = args.dest_scapy_port
+dest_scapy_ip = args.dest_scapy_ip
+
+context = zmq.Context()
+
+# Socket to talk to server
+print 'Connecting:'
+socket = context.socket(zmq.REQ)
+socket.connect("tcp://"+str(dest_scapy_ip)+":"+str(dest_scapy_port))
+try:
+ while True:
+ command = raw_input("enter RPC command [enter quit to exit]:\n")
+ if (command == 'quit'):
+ break
+ user_parameter = raw_input("input for command [should be left blank if not needed]:\n")
+ json_rpc_req = { "jsonrpc":"2.0","method": command ,"params":[user_parameter], "id":"1"}
+ request = json.dumps(json_rpc_req)
+ print("Sending request in json format %s" % request)
+ socket.send(request)
+
+ # Get the reply.
+ message = socket.recv()
+ print("Received reply %s [ %s ]" % (request, message))
+except KeyboardInterrupt:
+ print('Terminated By Ctrl+C')
+ socket.close()
+ context.destroy()
+
|