diff options
Diffstat (limited to 'scripts/automation/trex_control_plane/examples')
3 files changed, 189 insertions, 61 deletions
diff --git a/scripts/automation/trex_control_plane/examples/client_interactive_example.py b/scripts/automation/trex_control_plane/examples/client_interactive_example.py index 05028463..d21b2b15 100755 --- a/scripts/automation/trex_control_plane/examples/client_interactive_example.py +++ b/scripts/automation/trex_control_plane/examples/client_interactive_example.py @@ -15,7 +15,7 @@ import errno class InteractiveTRexClient(cmd.Cmd): - intro = termstyle.green("\nInteractive shell to play with Cisco's T-Rex API.\nType help to view available pre-defined scenarios\n(c) All rights reserved.\n") + 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 ): @@ -33,89 +33,89 @@ class InteractiveTRexClient(cmd.Cmd): def do_push_files (self, filepaths): - """Pushes a custom file to be stored locally on T-Rex server.\nPush multiple files by spefiying their path separated by ' ' (space).""" + """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 T-Rex. ***".format (trex_files = ', '.join(filepaths)) ) + 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 T-Rex push_files method (success) ***") + print termstyle.green("*** End of TRex push_files method (success) ***") else: - print termstyle.magenta("*** End of T-Rex push_files method (failed) ***") + 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 T-Rex running parameters""" + """Outputs the default TRex running parameters""" pprint(self.DEFAULT_RUN_PARAMS) - print termstyle.green("*** End of default T-Rex running parameters ***") + print termstyle.green("*** End of default TRex running parameters ***") def do_show_run_params(self,line): - """Outputs the currently configured T-Rex running parameters""" + """Outputs the currently configured TRex running parameters""" pprint(self.run_params) - print termstyle.green("*** End of T-Rex running parameters ***") + print termstyle.green("*** End of TRex running parameters ***") def do_update_run_params(self, json_str): - """Updates provided parameters on T-Rex running configuration. Provide using JSON string""" + """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 T-Rex parameters update ***") + 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 T-Rex current status""" + """Prompts TRex current status""" print self.trex.get_running_status() - print termstyle.green("*** End of T-Rex status prompt ***") + 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 t-rex server from client""" + """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 T-Rex is currently reserved or not""" + """Prompts if TRex is currently reserved or not""" if self.trex.is_reserved(): - print "T-Rex is reserved" + print "TRex is reserved" else: - print "T-Rex is NOT reserved" + print "TRex is NOT reserved" print termstyle.green("*** End of reservation status prompt ***") def do_reserve_trex (self, user): - """Reserves the usage of T-Rex to a certain 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("*** T-Rex reserved successfully ***") + 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 T-Rex to a certain 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("*** T-Rex reservation canceled successfully ***") + print termstyle.green("*** TRex reservation canceled successfully ***") except TRexException as inst: print termstyle.red(inst) def do_restore_run_default (self, line): - """Restores original T-Rex running configuration""" + """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 T-Rex and sample server until run is done.""" - print termstyle.green("*** Starting T-Rex run_until_finish scenario ***") + """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 @@ -123,15 +123,15 @@ class InteractiveTRexClient(cmd.Cmd): 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 T-Rex run ***") + 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 T-Rex and sample server manually until run is done.""" - print termstyle.green("*** Starting T-Rex run and manually poll scenario ***") + """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: @@ -145,7 +145,7 @@ class InteractiveTRexClient(cmd.Cmd): # do WHATEVER here time.sleep(sample_rate) - print termstyle.green("*** End of T-Rex run ***") + 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: @@ -153,8 +153,8 @@ class InteractiveTRexClient(cmd.Cmd): def do_run_until_condition (self, sample_rate): - """Starts T-Rex and sample server until condition is satisfied.""" - print termstyle.green("*** Starting T-Rex run until condition is satisfied scenario ***") + """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 @@ -166,55 +166,55 @@ class InteractiveTRexClient(cmd.Cmd): 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 T-Rex run ***") + 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 T-Rex run and once in 'Running' mode, return to cmd prompt""" - print termstyle.green("*** Starting T-Rex run, wait until in 'Running' state ***") + """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 (T-Rex is probably still running!) ***") + 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 T-Rex current data dump (if T-Rex is running) and prompts and short version of latest result_obj""" - print termstyle.green("*** Trying T-Rex single poll ***") + """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("T-Rex isn't currently running.") - print termstyle.green("*** End of scenario (T-Rex is posssibly still running!) ***") + 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 T-Rex run (if T-Rex is currently running)""" - print termstyle.green("*** Starting T-Rex termination ***") + """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 (T-Rex is not running now) ***") + 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 T-Rex process (if exists) on the server.""" - print termstyle.green("*** Starting T-Rex termination ***") + """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 (T-Rex is not running now) ***") + print termstyle.green("*** End of scenario (TRex is not running now) ***") elif ret is None: - print termstyle.magenta("*** End of scenario (T-Rex termination aborted) ***") + print termstyle.magenta("*** End of scenario (TRex termination aborted) ***") else: - print termstyle.red("*** End of scenario (T-Rex termination failed) ***") + print termstyle.red("*** End of scenario (TRex termination failed) ***") def do_exit(self, arg): """Quits the application""" @@ -223,20 +223,20 @@ class InteractiveTRexClient(cmd.Cmd): if __name__ == "__main__": - parser = ArgumentParser(description = termstyle.cyan('Run T-Rex client API demos and scenarios.'), + 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 T-Rex server.", + 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 T-Rex server listens. Default port is 8090.", action="store") + 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 T-Rex client. Default is: OFF.", + action="store_true", help="Switch ON verbose option at TRex client. Default is: OFF.", default = False ) args = parser.parse_args() @@ -248,7 +248,7 @@ if __name__ == "__main__": exit(-1) except socket.error, e: if e.errno == errno.ECONNREFUSED: - raise socket.error(errno.ECONNREFUSED, "Connection from T-Rex server was terminated. Please make sure the server is up.") + 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/interactive_stateless.py b/scripts/automation/trex_control_plane/examples/interactive_stateless.py new file mode 100644 index 00000000..e64b4755 --- /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 = CTRexStatelessClient(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 index 7e7f6139..acaa95d3 100755 --- a/scripts/automation/trex_control_plane/examples/pkt_generation_for_trex.py +++ b/scripts/automation/trex_control_plane/examples/pkt_generation_for_trex.py @@ -2,7 +2,7 @@ ###################################################################################### ### ### -### T-Rex end-to-end demo script, written by T-Rex dev-team ### +### 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) ### ### ### @@ -33,13 +33,13 @@ def pkts_to_pcap (pcap_filename, packets): def main (args): - # instantiate T-Rex client + # 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 T-Rex traffic. + # 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 "==================" @@ -50,7 +50,7 @@ def main (args): 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 T-Rex server + 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 @@ -65,12 +65,12 @@ def main (args): yaml_obj.dump() if args.steps: - print "\nNext step: run T-Rex with provided files." + 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 T-Rex..." + print "\nStarting TRex..." trex.start_trex(c = 2, m = 1.5, nc = True, @@ -80,8 +80,8 @@ def main (args): l = 1000) if args.verbose: - print "T-Rex state changed to 'Running'." - print "Sampling T-Rex in 0.2 samples/sec (single sample every 5 secs)" + 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): @@ -92,14 +92,14 @@ def main (args): if __name__ == "__main__": - parser = ArgumentParser(description = 'Run T-Rex client API end-to-end example.', + 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 T-Rex client. Default is: OFF.", + 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 |