Exemplo n.º 1
0
dictStreamBlockInfo = stc.perform("StreamBlockGetInfo", StreamBlock=hStreamBlock)

for szName in dictStreamBlockInfo:
    print "\t", szName, "\t", dictStreamBlockInfo[szName]

print "\n\n"


# Configure generator.
print "Configuring Generator"
hGeneratorConfig = stc.get(hGenerator, "children-GeneratorConfig")

stc.config(hGeneratorConfig, \
          DurationMode="BURSTS", \
          BurstSize=1, \
          Duration=100, \
          LoadMode="FIXED", \
          FixedLoad=100, \
          LoadUnit="PERCENT_LINE_RATE", \
          SchedulingMode="PORT_BASED")

# Analyzer Configuration.
print "Configuring Analyzer"
hAnalyzerConfig = stc.get(hAnalyzer, "children-AnalyzerConfig")

# Subscribe to realtime results.
print "Subscribe to results"
hAnaResults = stc.subscribe(Parent=hProject, \
            ConfigType="Analyzer", \
            resulttype="AnalyzerPortResults",  \
            filenameprefix="Analyzer_Port_Results")
def main():
    parser = argparse.ArgumentParser()
    # Required parameters
    requirednamed = parser.add_argument_group("required named arguments")
    requirednamed.add_argument("--lab_server_addr",
                               required=True,
                               help="The IP address of the Spirent Lab Server",
                               dest="lab_server_addr")
    requirednamed.add_argument("--license_server_addr",
                               required=True,
                               help="The IP address of the Spirent License Server",
                               dest="license_server_addr")
    requirednamed.add_argument("--east_chassis_addr",
                               required=True,
                               help="The TestCenter chassis IP address to use for the east test port",
                               dest="east_chassis_addr")
    requirednamed.add_argument("--east_slot_num",
                               type=positive_int,
                               required=True,
                               help="The TestCenter slot number to use for the east test port",
                               dest="east_slot_num")
    requirednamed.add_argument("--east_port_num",
                               type=positive_int,
                               required=True,
                               help="The TestCenter port number to use for the east test port",
                               dest="east_port_num")
    requirednamed.add_argument("--west_chassis_addr",
                               required=True,
                               help="The TestCenter chassis IP address to use for the west test port",
                               dest="west_chassis_addr")
    requirednamed.add_argument("--west_slot_num",
                               type=positive_int,
                               required=True,
                               help="The TestCenter slot number to use for the west test port",
                               dest="west_slot_num")
    requirednamed.add_argument("--west_port_num",
                               type=positive_int,
                               required=True,
                               help="The TestCenter port number to use for the west test port",
                               dest="west_port_num")
    # Optional parameters
    optionalnamed = parser.add_argument_group("optional named arguments")
    optionalnamed.add_argument("--test_session_name",
                               required=False,
                               default="RFC2544 East-West Throughput",
                               help="The friendly name to identify the Spirent Lab Server test session",
                               dest="test_session_name")
    optionalnamed.add_argument("--results_dir",
                               required=False,
                               default="./Results",
                               help="The directory to copy results to",
                               dest="results_dir")
    optionalnamed.add_argument("--csv_results_file_prefix",
                               required=False,
                               default="Rfc2544Tput",
                               help="The prefix for the CSV results files",
                               dest="csv_results_file_prefix")
    optionalnamed.add_argument("--num_trials",
                               type=positive_int,
                               required=False,
                               default=1,
                               help="The number of trials to execute during the test",
                               dest="num_trials")
    optionalnamed.add_argument("--trial_duration_sec",
                               type=positive_int,
                               required=False,
                               default=60,
                               help="The duration of each trial executed during the test",
                               dest="trial_duration_sec")
    optionalnamed.add_argument("--traffic_pattern",
                               required=False,
                               choices=["BACKBONE", "MESH", "PAIR"],
                               default="PAIR",
                               help="The traffic pattern between endpoints",
                               dest="traffic_pattern")
    optionalnamed.add_argument("--search_mode",
                               required=False,
                               choices=["COMBO", "STEP", "BINARY"],
                               default="BINARY",
                               help="The search mode used to find the throughput rate",
                               dest="search_mode")
    optionalnamed.add_argument("--learning_mode",
                               required=False,
                               choices=["AUTO", "L2_LEARNING", "L3_LEARNING", "NONE"],
                               default="AUTO",
                               help="The learning mode used during the test, default = 'NONE'",
                               dest="learning_mode")
    optionalnamed.add_argument("--rate_lower_limit_pct",
                               type=percent_float,
                               required=False,
                               default=1.0,
                               help="The minimum percent line rate that will be used during the test",
                               dest="rate_lower_limit_pct")
    optionalnamed.add_argument("--rate_upper_limit_pct",
                               type=percent_float,
                               required=False,
                               default=99.0,
                               help="The maximum percent line rate that will be used during the test",
                               dest="rate_upper_limit_pct")
    optionalnamed.add_argument("--rate_initial_pct",
                               type=percent_float,
                               required=False,
                               default=99.0,
                               help="If Search Mode is BINARY, the percent line rate that will be used at the start of the test",
                               dest="rate_initial_pct")
    optionalnamed.add_argument("--rate_step_pct",
                               type=percent_float,
                               required=False,
                               default=10.0,
                               help="If SearchMode is STEP, the percent load increase per step",
                               dest="rate_step_pct")
    optionalnamed.add_argument("--resolution_pct",
                               type=percent_float,
                               required=False,
                               default=1.0,
                               help="The minimum percentage of load adjustment between iterations",
                               dest="resolution_pct")
    optionalnamed.add_argument("--frame_size_list",
                               type=lambda s: [int(item) for item in s.split(',')],
                               required=False,
                               default=[64, 128, 256],
                               help="A comma-delimited list of frame sizes",
                               dest="frame_size_list")
    optionalnamed.add_argument("--acceptable_frame_loss_pct",
                               type=percent_float,
                               required=False,
                               default=0.0,
                               help="The maximum acceptable frame loss percent in any iteration",
                               dest="acceptable_frame_loss_pct")
    optionalnamed.add_argument("--east_intf_addr",
                               required=False,
                               default="192.85.1.3",
                               help="The address to assign to the first emulated device interface on the first east port",
                               dest="east_intf_addr")
    optionalnamed.add_argument("--east_intf_gateway_addr",
                               required=False,
                               default="192.85.1.53",
                               help="The gateway address to assign to the first emulated device interface on the first east port",
                               dest="east_intf_gateway_addr")
    optionalnamed.add_argument("--west_intf_addr",
                               required=False,
                               default="192.85.1.53",
                               help="The address to assign to the first emulated device interface on the first west port",
                               dest="west_intf_addr")
    optionalnamed.add_argument("--west_intf_gateway_addr",
                               required=False,
                               default="192.85.1.53",
                               help="The gateway address to assign to the first emulated device interface on the first west port",
                               dest="west_intf_gateway_addr")
    parser.add_argument("-v",
                        "--verbose",
                        required=False,
                        default=False,
                        help="More output during operation when present",
                        action="store_true",
                        dest="verbose")
    args = parser.parse_args()

    if args.verbose:
        print("Make sure results directory exists")
    create_dir(args.results_dir)

    # Load Spirent Test Center library
    from StcPython import StcPython
    stc = StcPython()

    tx_port_loc = "//%s/%s/%s" % (args.east_chassis_addr,
                                  args.east_slot_num,
                                  args.east_port_num)
    rx_port_loc = "//%s/%s/%s" % (args.west_chassis_addr,
                                  args.west_slot_num,
                                  args.west_port_num)

    # This line will write the TestCenter commands to a log file
    stc.config("automationoptions", logto="test-op", loglevel="DEBUG")

    # Retrieve and display the current API version.
    if args.verbose:
        print ("SpirentTestCenter system version: %s" % stc.get("system1", "version"))

    create_session(stc, args.lab_server_addr, args.test_session_name)

    try:
        device_list = []

        if args.verbose:
            print("Bring up license server")
        license_mgr = stc.get("system1", "children-licenseservermanager")
        if args.verbose:
            print("license_mgr = %s" % license_mgr)
        stc.create("LicenseServer", under=license_mgr, server=args.license_server_addr)

        # Create the root project object
        if args.verbose:
            print ("Creating project ...")
        project = stc.get("System1", "children-Project")

        # Create ports
        if args.verbose:
            print ("Creating ports ...")
        east_chassis_port = stc.create("port",
                                       under=project,
                                       location=tx_port_loc,
                                       useDefaultHost="False")
        west_chassis_port = stc.create("port",
                                       under=project,
                                       location=rx_port_loc,
                                       useDefaultHost="False")

        if args.verbose:
            print ("Creating devices...")
        # Create emulated genparam for east port
        east_device_gen_params = stc.create("EmulatedDeviceGenParams",
                                            under=project,
                                            Port=east_chassis_port)
        # Create the DeviceGenEthIIIfParams object
        stc.create("DeviceGenEthIIIfParams",
                   under=east_device_gen_params)
        # Configuring Ipv4 interfaces
        stc.create("DeviceGenIpv4IfParams",
                   under=east_device_gen_params,
                   Addr=args.east_intf_addr,
                   Gateway=args.east_intf_gateway_addr)
        # Create Devices using the Device Wizard
        device_gen_config = stc.perform("DeviceGenConfigExpand",
                                        DeleteExisting="No",
                                        GenParams=east_device_gen_params)
        # Append to the device list
        device_list.append(device_gen_config['ReturnList'])

        # Create emulated genparam for west port
        west_device_gen_params = stc.create("EmulatedDeviceGenParams",
                                            under=project,
                                            Port=west_chassis_port)
        # Create the DeviceGenEthIIIfParams object
        stc.create("DeviceGenEthIIIfParams",
                   under=west_device_gen_params)
        # Configuring Ipv4 interfaces
        stc.create("DeviceGenIpv4IfParams",
                   under=west_device_gen_params,
                   Addr=args.west_intf_addr,
                   Gateway=args.west_intf_gateway_addr)
        # Create Devices using the Device Wizard
        device_gen_config = stc.perform("DeviceGenConfigExpand",
                                        DeleteExisting="No",
                                        GenParams=west_device_gen_params)
        # Append to the device list
        device_list.append(device_gen_config['ReturnList'])

        if args.verbose:
            print(device_list)

        # Create the RFC 2544 throughput test
        if args.verbose:
            print ("Set up the RFC2544 throughput test...")
        stc.perform("Rfc2544SetupThroughputTestCommand",
                    AcceptableFrameLoss=args.acceptable_frame_loss_pct,
                    Duration=args.trial_duration_sec,
                    FrameSizeList=args.frame_size_list,
                    LearningMode=args.learning_mode,
                    NumOfTrials=args.num_trials,
                    RateInitial=args.rate_initial_pct,
                    RateLowerLimit=args.rate_lower_limit_pct,
                    RateStep=args.rate_step_pct,
                    RateUpperLimit=args.rate_upper_limit_pct,
                    Resolution=args.resolution_pct,
                    SearchMode=args.search_mode,
                    TrafficPattern=args.traffic_pattern)

        # Save the configuration
        stc.perform("SaveToTcc", Filename="2544.tcc")

        # Connect to the hardware...
        stc.perform("AttachPorts", portList=stc.get("system1.project", "children-port"), autoConnect="TRUE")

        # Apply configuration.
        if args.verbose:
            print("Apply configuration...")
        stc.apply

        if args.verbose:
            print("Starting the sequencer...")
        stc.perform("SequencerStart")

        # Wait for sequencer to finish
        print("Starting test... Please wait for the test to complete...")
        stc.waitUntilComplete()
        print("The test has completed... Saving results...")

        # Determine what the results database filename is...
        lab_server_resultsdb = stc.get("system1.project.TestResultSetting", "CurrentResultFileName")

        if args.verbose:
            print("The lab server results database is %s" % lab_server_resultsdb)

        stc.perform("CSSynchronizeFiles",
                    DefaultDownloadDir=args.results_dir)

        resultsdb = args.results_dir + lab_server_resultsdb.split("/Results")[1]

        print("The local summary DB file has been saved to %s" % resultsdb)

        # The returns the "RFC2544ThroughputTestResultDetailedSummaryView" table view from the results database.
        # There are other views available.
        resultsdict = stc.perform("QueryResult",
                                  DatabaseConnectionString=resultsdb,
                                  ResultPath="RFC2544ThroughputTestResultDetailedSummaryView")
        if args.verbose:
            print("resultsdict[\"Columns\"]: %s" % resultsdict["Columns"])
            print("resultsdict[\"Output\"]: %s" % resultsdict["Output"])

        if args.verbose:
            print("Result paths: %s" % stc.perform("GetTestResultSettingPaths"))

        # Write results to csv
        if args.verbose:
            print("Writing CSV file to results directory %s" % args.results_dir)
        write_query_results_to_csv(args.results_dir, args.csv_results_file_prefix, resultsdict)

    except Exception, e:
        print("Exception: %s" % str(e))
        # destroy_session(stc, args.lab_server_addr, args.test_session_name)
        raise
Exemplo n.º 3
0
#################################

# All possible generator, analyzer, rxstreamsummary port result attributes:
generator_attributes = 'totalframecount totaloctetcount generatorframecount generatoroctetcount generatorsigframecount generatorundersizeframecount generatoroversizeframecount generatorjumboframecount totalframerate totaloctetrate generatorframerate generatoroctetrate generatorsigframerate generatorundersizeframerate generatoroversizeframerate generatorjumboframerate generatorcrcerrorframecount generatorl3checksumerrorcount generatorl4checksumerrorcount generatorcrcerrorframerate generatorl3checksumerrorrate generatorl4checksumerrorrate totalipv4framecount totalipv6framecount totalmplsframecount generatoripv4framecount generatoripv6framecount generatorvlanframecount generatormplsframecount totalipv4framerate totalipv6framerate totalmplsframerate generatoripv4framerate generatoripv6framerate generatorvlanframerate generatormplsframerate totalbitrate generatorbitrate l1bitcount l1bitrate pfcframecount pfcpri0framecount pfcpri1framecount pfcpri2framecount pfcpri3framecount pfcpri4framecount pfcpri5framecount pfcpri6framecount pfcpri7framecount l1bitratepercent'

analyzer_attributes = 'totalframecount totaloctetcount sigframecount undersizeframecount oversizeframecount jumboframecount minframelength maxframelength pauseframecount totalframerate totaloctetrate sigframerate undersizeframerate oversizeframerate jumboframerate pauseframerate fcserrorframecount ipv4checksumerrorcount tcpchecksumerrorcount udpchecksumerrorcount prbsfilloctetcount prbsbiterrorcount fcserrorframerate ipv4checksumerrorrate tcpchecksumerrorrate udpchecksumerrorrate prbsfilloctetrate prbsbiterrorrate ipv4framecount ipv6framecount ipv6overipv4framecount tcpframecount udpframecount mplsframecount icmpframecount vlanframecount ipv4framerate ipv6framerate ipv6overipv4framerate tcpframerate udpframerate mplsframerate icmpframerate vlanframerate trigger1count trigger1rate trigger2count trigger2rate trigger3count trigger3rate trigger4count trigger4rate trigger5count trigger5rate trigger6count trigger6rate trigger7count trigger7rate trigger8count trigger8rate combotriggercount combotriggerrate totalbitrate prbsbiterrorratio vlanframerate l1bitcount l1bitrate pfcframecount fcoeframecount pfcframerate fcoeframerate pfcpri0framecount pfcpri1framecount pfcpri2framecount pfcpri3framecount pfcpri4framecount pfcpri5framecount pfcpri6framecount pfcpri7framecount pfcpri0quanta pfcpri1quanta pfcpri2quanta pfcpri3quanta pfcpri4quanta pfcpri5quanta pfcpri6quanta pfcpri7quanta prbserrorframecount prbserrorframerate userdefinedframecount1 userdefinedframerate1 userdefinedframecount2 userdefinedframerate2 userdefinedframecount3 userdefinedframerate3 userdefinedframecount4 userdefinedframerate4 userdefinedframecount5 userdefinedframerate5 userdefinedframecount6 userdefinedframerate6 l1bitratepercent outseqframecount preambletotalbytes preambleminlength preamblemaxlength droppedframecount inorderframecount reorderedframecount duplicateframecount lateframecount firstarrivaltime lastarrivaltime'

rxstreamsummaryresults_attributes = 'avginterarrivaltime avgjitter avglatency bitcount bitrate cellcount cellrate comp16_1 comp16_2 comp16_3 comp16_4 comp32 countertimestamp droppedframecount droppedframepercent droppedframepercentrate droppedframerate duplicateframecount duplicateframerate expectedseqnum fcserrorframecount fcserrorframerate firstarrivaltime framecount framerate histbin10count histbin10name histbin10rate histbin11count histbin11name histbin11rate histbin12count histbin12name histbin12rate histbin13count histbin13name histbin13rate histbin14count histbin14name histbin14rate histbin15count histbin15name histbin15rate histbin16count histbin16name histbin16rate histbin1count histbin1name histbin1rate histbin2count histbin2name histbin2rate histbin3count histbin3name histbin3rate histbin4count histbin4name histbin4rate histbin5count histbin5name histbin5rate histbin6count histbin6name histbin6rate histbin7count histbin7name histbin7rate histbin8count histbin8name histbin8rate histbin9count histbin9name histbin9rate inorderframecount inorderframerate inseqframecount inseqframerate ipv4checksumerrorcount ipv4checksumerrorrate l1bitcount l1bitrate lastarrivaltime lastseqnum lateframecount lateframerate maxframelength maxinterarrivaltime maxjitter maxlatency minframelength mininterarrivaltime minjitter minlatency octetcount octetrate outseqframecount outseqframerate portstrayframes prbsbiterrorcount prbsbiterrorrate prbsbiterrorratio prbserrorframecount prbserrorframerate prbsfilloctetcount prbsfilloctetrate reorderedframecount reorderedframerate rfc4689absoluteavgjitter rxport seqrunlength shorttermavginterarrivaltime shorttermavgjitter shorttermavglatency sigframecount sigframerate streamindex tcpudpchecksumerrorcount tcpudpchecksumerrorrate totalinterarrivaltime totaljitter totaljitterrate totallatency'
#################################

# Create Spirent API instance
stc = StcPython()
# Create project - the root object
hProject = stc.create("project")
# Print WARN and ERROR messages
stc.config("automationoptions", logTo='stdout', logLevel='WARN')

# Load configuration from XML
stc.perform('loadfromxml', filename=xml_filename)
# Search for objects of type 'Port' in the configuration and extract them
rv = stc.perform('GetObjects', ClassName='Port', Condition='IsVirtual=false')
ports = str.split(rv['ObjectList'])
if len(ports) != 2:
    print("Error: failed to find two ports in configuration\n")
    exit(1)

# Configure ports, set results dir, set sequencer to stop on error
stc.config(ports[0], location=port1_location)
stc.config(ports[1], location=port2_location)
stc.config(hProject + '.testResultSetting',
           saveResultsRelativeTo='NONE',
Exemplo n.º 4
0
import datetime
import os.path

# Point to the StcPython.py file in your Spirent TestCenter installation.
# You first need to either set the environment variable "STC_PRIVATE_INSTALL_DIR",
# or change the StcPython.py file ("STC_PRIVATE_INSTALL_DIR") to point to your
# installation.
# eg: os.environ['STC_PRIVATE_INSTALL_DIR'] = '/home/mjefferson/spirent/stc/stc4.59/'

print "Loading the Spirent TestCenter API..."
sys.path.append('/home/mjefferson/spirent/stc/stc4.61/API/Python')
from StcPython import StcPython
stc = StcPython()

# Instruct the API to not display all commands to STDOUT.
stc.config("AutomationOptions", logTo="stcapi.log", logLevel="INFO")

stc.perform("LoadFromDatabaseCommand",
            DatabaseConnectionString="capturetest.tcc")

# Remap port locations if necessary.
for port, location in zip(
        stc.get("system1.project", "children-port").split(), port_locations):
    print "Remapping " + port + " to " + location
    stc.config(port, location=location)

# Connect to the hardware.
stc.perform("AttachPorts",
            AutoConnect="true",
            PortList=stc.get("system1.project", "children-port"))
stc.apply()
Exemplo n.º 5
0
####
###############################################################################

if labserverip:
    # If you are using a lab server, connect to it now.
    print("Connecting to Lab Server")
    stc.perform("CSTestSessionConnect",
                host=labserverip,
                TestSessionName="sample",
                CreateNewTestSession="true")

    # Terminate the Lab Server session when the last client disconnects.
    stc.perform("TerminateBll", TerminateType="ON_LAST_DISCONNECT")

# Instruct the API to not display all commands to STDOUT.
stc.config("AutomationOptions", logTo="stcapi.log", logLevel="INFO")

# Save the project handle for later. This is not strictly necessary.
project = stc.get("system1", "children-project")

# Create a port for each location specified.
for location in locationlist:
    # If you are connecting to a single-speed port, this is all you need to do.
    # If you are connecting to a multi-speed port, you may need to create the appropriate phy object (e.g., Ethernet10GigFiber).
    port = stc.create("port", under=project, location=location)

    # Configure the port rate to 100% line-rate.
    stc.config(port + ".generator.generatorconfig",
               fixedload=100,
               loadunit="PERCENT_LINE_RATE")
Exemplo n.º 6
0
import sys
import os.path

# Point to the StcPython.py file in your Spirent TestCenter installation.
# You first need to either set the environment variable "STC_PRIVATE_INSTALL_DIR",
# or change the StcPython.py file ("STC_PRIVATE_INSTALL_DIR") to point to your
# installation.
# eg: os.environ['STC_PRIVATE_INSTALL_DIR'] = '/home/mjefferson/spirent/stc/stc4.59/'

print "Loading the Spirent TestCenter API..."
sys.path.append('/home/mjefferson/spirent/stc/stc4.59/API/Python')
from StcPython import StcPython
stc = StcPython()

# Instruct the API to not display all log entries to STDOUT.
stc.config("AutomationOptions", logTo="stcapi.log", logLevel="INFO")

# Create the configuration from scratch.
print "Creating the configuration from scratch..."
project = stc.get("system1", "children-project")

# Start by creating two ports. port1 is the Tx port, and port2 is the Rx.
port1 = stc.create("port", under=project, location="10.140.99.120/1/1")
port2 = stc.create("port", under=project, location="10.140.99.121/1/1")

# Create a single Emulated Device on each port.
# The "IfStack" is the space-separated list of interface objects used by the device.
# It is sorted top-down, meaning that the EthIIIf object will be the last element of the list.
#   eg: EthIIIf, VlanIf, IPv4If, IPv6If, GREIf, L2tpv2If, MplsIf, etc
result = stc.perform("DeviceCreate",
                     ParentList=project,
Exemplo n.º 7
0
#stc.reserve('//172.33.42.4/4/3')

print 'Create a Project  - root'

project = stc.create('project')

print 'Get Project attributes'

projectAtt = stc.get(project, 'name')

print projectAtt
print 'Create Ports under', project

port1 = stc.create('port', under=project)
print 'Configure Port locations'
stc.config(port1, location="//%s/%s/%s" % (chassisAddress, slot, port))

print 'Creating StreamBlock on Port  1'
streamBlock = stc.create('streamBlock', under=port1)
generator = stc.get(port1, 'children-generator')

print 'Attaching Ports...'

stc.perform('AttachPorts', portList=[port1], autoConnect='TRUE')
stc.apply()

print 'Call Subscribe...'

port1GeneratorResult = stc.subscribe(
    Parent=project,
    ResultParent=port1,
Exemplo n.º 8
0
pdb.set_trace()

# Point to the StcPython.py file in your Spirent TestCenter installation.
# You first need to either set the environment variable "STC_PRIVATE_INSTALL_DIR",
# or change the StcPython.py file ("STC_PRIVATE_INSTALL_DIR") to point to your
# installation.
# eg: os.environ['STC_PRIVATE_INSTALL_DIR'] = '/home/mjefferson/spirent/stc/stc4.59/'

print "Loading the Spirent TestCenter API..."
sys.path.append('/home/mjefferson/spirent/stc/stc4.59/API/Python')
from StcPython import StcPython

stc = StcPython()

# Instruct the API to not display all commands to STDOUT.
stc.config("AutomationOptions", logTo="stcapi.log", logLevel="INFO")

if labserverip:
    print 'Connecting to Lab Server'
    stc.perform("CSTestSessionConnect",
                host=labserverip,
                TestSessionName="Training",
                OwnerId="matt",
                CreateNewTestSession="true")

    # Terminate the Lab Server session when the last client disconnects.
    stc.perform("TerminateBll", TerminateType="ON_LAST_DISCONNECT")

if tcc_configuration:
    print "Loading TCC configuration ", tcc_configuration, ' loading it now'
Exemplo n.º 9
0
stc = StcPython()

port1_location = "//neb-nickluong-01.calenglab.spirentcom.com/1/17"
port2_location = "//neb-nickluong-01.calenglab.spirentcom.com/1/25"

print("reserving ports")
ret = stc.perform("createandreserveports",
                  locationlist=[port1_location, port2_location])

hportlist = ret["PortList"].split()

hport1 = hportlist[0]
hport2 = hportlist[1]

print("config port1 lane 0 PRBS TxPattern as PRBS7")
stc.config("%s.l1configgroup.l1portprbs.l1laneprbspam4(1)" % hport1,
           TxPattern="PRBS7")

stc.apply()

stc.perform("startenhancedresultstestcommand")

query_json = {
    "definition": {
        "multi_result": {
            "filters": [],
            "groups": [],
            "orders": [
                "view.port_name_str_order ASC", "view.port_name_num_order ASC",
                "view.port_name_ip_order ASC",
                "view.port_name_hostname_order ASC",
                "view.port_name_slot_order ASC",
Exemplo n.º 10
0
class StcDriver(API):
   
    def __init__(self):
        #super(API, self).__init__()
        self.handle = StcPython()
        main.log.info("STC component initialized")

    def connect(self,**connectargs):
        for key in connectargs:
            vars(self)[key] = connectargs[key]

        self.name = self.options['name']
        main.log.info("Component name is "+self.name)
        connect_result = super(API,self).connect()
        main.log.info("Main dir "+main.logdir)
        self.logFileName = main.logdir+"/"+self.name+".session"
        main.log.info("Session log file is "+self.logFileName)
        self.handle.config('automationoptions', loglevel='info',logto=self.logFileName)
        main.log.info("Connected successfully")
        return main.TRUE
    
    def apply(self):
        try :
            main.log.info("apply the action")
            return self.handle.apply()
        except :
            main.log.error("Apply failed because of Exception"+str(sys.exc_info()[0]))
            return { 'result' : main.FALSE , 'error' : sys.exc_info()[0]}
    
    def create(self,objectTypeString,**arguments) :
        try :
            main.log.info("creating arguments") 
            #return { result : main.TRUE,return value : self.handle.create(objectTypeString,**arguments) }
            return self.handle.create(objectTypeString,**arguments)
            #return ReturnValue(main.TRUE,self.handle.create(objectTypeString,**arguments))
        except :
            main.log.error("Operation "+str(objectTypeString)+" failed because of exception "+str(sys.exc_info()[0]))
            return { 'result' : main.FALSE, 'error' : sys.exc_info()[0] }

    
    def config(self,handleString,**attributes) :
        try :
            main.log.info("Configure Port locations")
            self.handle.config(handleString,**attributes)
            #return { result : main.TRUE, return value : slef.handle.config(handleString,**attributes)}
            return self.handle.config(handleString,**attributes)
            #return ReturnValue(main.TRUE,self.handle.config(handleString,**attributes))
        except :
            main.log.error("Operation "+str(handleString)+" failed because of exception "+str(sys.exc_info()[0]))
            return { 'result' : main.FALSE, 'error' : sys.exc_info()[0] } 
    
    def get(self,handleString, attribute) :
        try :
            main.log.info("Getting attributes for "+str(handleString))
            #return { result : main.TRUE , return value : self.handle.get(handleString,attribute)}
            return self.handle.get(handleString, attribute)
            #return ReturnValue(main.TRUE,self.handle.get(handleString, attribute))
        except :
            main.log.error("operation"+str(handleString)+"failed because of exception"+str(sys.exc_info()[0]))
            return { 'result' :main.FALSE , 'error': sys.exc_info()[0]}

    def perform(self,commandNameString, **attribute) :
        try :
            main.log.info("Performing action "+str(commandNameString))
            #return { result : main.TRUE , return value : self.handle.perform(commandNameString,**attribute)}
            return self.handle.perform(commandNameString, **attribute)
            #return ReturnValue(main.TRUE , self.handle.perform(commandNameString,**attribute))
        except :
            main.log.error("Operation "+str(commandNameString)+" failed because of exception "+str(sys.exc_info()[0]))
            return { 'result' : main.FALSE, 'error' : sys.exc_info()[0] }
    
    def subscribe(self,**inputParams) :
        try :
            main.log.info("subscribe the result")
            #return { result : main.TRUE , return value : self.handle.subscribe(**inputParams)}
            return self.handle.subscribe(**inputParams)
            #return ReturnValue(main.TRUE,self.handle.subscribe(**inputParams))
        except :
            main.log.error("Operation failed because of exception "+str(sys.exc_info()[0]))
            return { 'result' : main.FALSE , 'error' : sys.exc_info()[0] }

    def disconnect(self,hostNameString) :
        try :
            main.log.info("disconnect")
            #return { result : main.TRUE ,return value : self.handle.disconnect(hostNameString)}
            return self.handle.disconnect(str(hostNameString))
            #return ReturnValue(main.TRUE,self.handle.disconnect(hostNameString))
        except :
            main.log.error("Operation failed because of exception "+str(sys.exc_info()[0]))
            return { 'result' : main.FALSE, 'error' : sys.exc_info()[0] }

    def sleep(self,numberSecondsInteger) :
        try :
            main.log.info("sleep time is")
            #return { result : main.TRUE , return value : self.handle.sleep(numberSecondsInteger)}
            return self.handle.sleep(numberSecondsInteger)
            #return ReturnValue(main.TRUE,self.handle.sleep(numberSecondsInteger))
        except :
            main.log.error("Operation failed because of exception "+str(sys.exc_info()[0]))
            return { 'result' : main.FALSE, 'error' : sys.exc_info()[0] }

    def unsubscribe(self,resultDataSetHandleString) :
        try :
            main.log.info("unsubscribe the ports"+str(resultDataSetHandleString))
            return self.handle.unsubscribe(str(resultDataSetHandleString))
            #return { result : main.TRUE , return value : self.handle.unsubscribe(resultDataSetHandleString)}
            #return ReturnValue(main.TRUE,self.handle.unsubscribe(resultDataSetHandleString))
        except :
            main.log.error("unsubscribe"+str(resultDataSetHandleString)+" failed because of exception "+str(sys.exc_info()[0]))
            return { 'result' : main.FALSE, 'error' : sys.exc_info()[0] }

    def delete(self,handleString) :
        try :
            main.log.info("Deleting ports"+str(handleString))
            return self.handle.delete(str(handleString))
            #return ReturnValue(main.TRUE,self.handle.delete(handleString))
        except :
            main.log.error("Deletion of "+str(handleString)+"failed because of exception "+str(sys.exc_info()[0]))
            return { 'result' : main.FALSE, 'error' : sys.exc_info()[0] }
    def parseresults(self,Attribute,CsvFile) :
        
        try :
            main.log.info("parsing the CSV file for the traffic results")                 
            totalrows = len(open('/home/sudheer-570/Desktop/sk/TestON/bin/Untitled/'+CsvFile).readlines())
            fp = open("/home/sudheer-570/Desktop/sk/TestON/bin/Untitled/"+CsvFile,'Ur')
            data_list = []
            attributes=[]
            attribute_values=[]
            for line in fp:
                data_list.append(line.strip().split(','))
            attribute_values=data_list[totalrows-1]
            attributes=data_list[totalrows-3]

            for index in range (0,100) :
                if attributes[index]==Attribute:
                    main.log.info("Given Attribute Name is:'"+Attribute+"'")
                    main.log.info("Attribute value is:'"+attribute_values[index]+"'")
                    result = attribute_values[index]
                    if result == '0' :
                        main.log.info("Traffic is not generated on this attribute :"+Attribute)
                        return main.FALSE
                    else :
                        return result
        except :
            main.log.error("operation failed because of"+str(sys.exc_info()[0]))
            return { 'result' : main.FALSE, 'error' : sys.exc_info()[0] }
sys.path.append('/home/mjefferson/spirent/stc/stc4.61/API/Python/')
from StcPython import StcPython
stc = StcPython()

port_traffic1 = stc.create("port", under="project1")
port_traffic2 = stc.create("port", under="project1")

# NOTE: The FrameConfig PDUs are case-sensitive.
#       Examples are: EthernetII, Vlan, IPv4, IPv6, Mpls, Tcp, UDP, PPP, Gre, etc. There are many more.
# Default: "EthernetII IPv4"}
streamblock1 = stc.create("StreamBlock",
                          under=port_traffic1,
                          FrameConfig="EthernetII IPv4")
stc.get(streamblock1)
stc.config(streamblock1 + ".ethernet:EthernetII",
           srcMac="00:11:94:00:00:02",
           dstMac="00:12:94:00:00:02")
stc.config(streamblock1 + ".ipv4:IPv4",
           sourceAddr="192.168.11.2",
           destAddr="192.168.12.2",
           gateway="192.168.11.1",
           prefixlength="24",
           destprefixlength="24")

streamblock2 = stc.create("StreamBlock",
                          under=port_traffic2,
                          FrameConfig="EthernetII IPv4")
stc.get(streamblock2)
stc.config(streamblock2 + ".ethernet:EthernetII",
           srcMac="00:12:94:00:00:02",
           dstMac="00:11:94:00:00:02")
# stc.perform("AttachPorts", AutoConnect="true", PortList=stc.get(project, "children-port"))
# stc.apply()

stc.perform("GeneratorStart")
time.sleep(5)

rds = sbrds()

for count in range(3):
    stc.perform("RefreshResultView", ResultDataSet=rds)

    pages = int(stc.get(rds, "TotalPageCount"))

    for page in range(1, pages + 1):
        print("Page=", page)
        stc.config(rds, PageNumber=page)
        stc.apply()
        time.sleep(1)

        # stc.perform("RefreshResultView", ResultDataSet=txrds)
        # stc.perform("RefreshResultView", ResultDataSet=rxrds)

        for result in stc.get(rds, "ResultHandleList").split():
            regex = re.compile("txstreamblockresults.")
            if re.match(regex, result):
                parent = stc.get(result, "parent")
                rxresult = stc.get(result, "associatedresult-Targets")
                print(parent, " Tx=", stc.get(result, "FrameCount"), " Rx=",
                      stc.get(rxresult, "FrameCount"), " Rate=",
                      stc.get(rxresult, "FrameRate"))
Exemplo n.º 13
0
                              "L1BitRate")
        rxl2bitrate = stc.get(port + ".Analyzer.AnalyzerPortResults",
                              "TotalBitRate")

        print(port + " TxFrameRate=" + txframerate + " TxL1BitRate=" +
              txl1bitrate + " TxL2BitRate=" + txl2bitrate)
        print(port + " RxFrameRate=" + rxframerate + " RxL1BitRate=" +
              rxl1bitrate + " RxL2BitRate=" + rxl2bitrate)

        # Display the stream rates...
        print("")
        print("Stream Results")
        totalpages = int(stc.get(streamrds, "TotalPageCount"))
        for page in range(1, totalpages + 1):
            print("Page " + str(page) + " of " + str(totalpages))
            stc.config(streamrds, PageNumber=page)
            stc.apply()
            # You must wait a certain amount of time for the result objects to be populated.
            time.sleep(4)

            # Now grab the results.
            for txresult in stc.get(streamrds, "ResultHandleList").split():
                regex = re.compile("txstreamresults.")
                if re.match(regex, txresult):
                    rxresult = stc.get(txresult, "associatedresult-Targets")

                    streamblock = stc.get(txresult, "parent")

                    txframerate = stc.get(txresult, "FrameRate")
                    txl1bitrate = stc.get(txresult, "L1BitRate")
                    txl2bitrate = stc.get(txresult, "BitRate")
Exemplo n.º 14
0
#import time
import os.path

# Point to the StcPython.py file in your Spirent TestCenter installation.
# You first need to either set the environment variable "STC_PRIVATE_INSTALL_DIR",
# or change the StcPython.py file ("STC_PRIVATE_INSTALL_DIR") to point to your
# installation.
# eg: os.environ['STC_PRIVATE_INSTALL_DIR'] = '/home/mjefferson/spirent/stc/stc4.59/'

print "Loading the Spirent TestCenter API..."
sys.path.append('/home/mjefferson/spirent/stc/stc4.59/API/Python')
from StcPython import StcPython
stc = StcPython()

# Instruct the API to not display all commands to STDOUT.
stc.config("AutomationOptions", logTo="stcapi.log", logLevel="INFO")

# Create the configuration from scratch.
print "Creating the configuration from scratch..."
project = stc.get("system1", "children-project")

# Start by creating two ports. port1 is the Tx port, and port2 is the Rx.
port1 = stc.create("port", under=project, location="10.140.99.120/1/1")
port2 = stc.create("port", under=project, location="10.140.99.121/1/1")

# Create a single Emulated Device on each port.
# The "IfStack" is the space-separated list of interface objects used by the device.
# It is sorted top-down, meaning that the EthIIIf object will be the last element of the list.
#   eg: EthIIIf, VlanIf, IPv4If, IPv6If, GREIf, L2tpv2If, MplsIf, etc
# The "IfCount" is a space-separated list indicating how many interface object instances to create for each
# element of the IfStack. This list is ordered in the same way as the IfStack.
dictStreamBlockInfo = stc.perform("StreamBlockGetInfo", StreamBlock=hStreamBlock)

for szName in dictStreamBlockInfo:
    print "\t", szName, "\t", dictStreamBlockInfo[szName]

print "\n\n"


# Configure generator.
print "Configuring Generator"
hGeneratorConfig = stc.get(hGenerator, "children-GeneratorConfig")

stc.config(hGeneratorConfig, \
          DurationMode="BURSTS", \
          BurstSize=1, \
          Duration=100, \
          LoadMode="FIXED", \
          FixedLoad=100, \
          LoadUnit="PERCENT_LINE_RATE", \
          SchedulingMode="PORT_BASED")

# Analyzer Configuration.
print "Configuring Analyzer"
hAnalyzerConfig = stc.get(hAnalyzer, "children-AnalyzerConfig")

# Subscribe to realtime results.
print "Subscribe to results"
hAnaResults = stc.subscribe(Parent=hProject, \
            ConfigType="Analyzer", \
            resulttype="AnalyzerPortResults",  \
            filenameprefix="Analyzer_Port_Results")