1 # Copyright 2016 Spirent Communications.
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
16 @author Spirent Communications
18 This test automates the RFC2544 tests using the Spirent
19 TestCenter REST APIs. This test supports Python 3.4
26 # Logger Configuration
27 logger = logging.getLogger(__name__)
31 """Create the directory as specified in path """
32 if not os.path.exists(path):
36 logger.error("Failed to create directory %s: %s", path, str(e))
40 def write_query_results_to_csv(results_path, csv_results_file_prefix,
42 """ Write the results of the query to the CSV """
43 create_dir(results_path)
44 filec = os.path.join(results_path, csv_results_file_prefix + ".csv")
45 with open(filec, "wb") as f:
46 f.write(query_results["Columns"].replace(" ", ",") + "\n")
47 for row in (query_results["Output"].replace("} {", ",").
48 replace("{", "").replace("}", "").split(",")):
49 f.write(row.replace(" ", ",") + "\n")
52 def positive_int(value):
53 """ Positive Integer type for Arguments """
56 raise argparse.ArgumentTypeError(
57 "%s is an invalid positive int value" % value)
61 def percent_float(value):
62 """ Floating type for Arguments """
64 if pvalue < 0.0 or pvalue > 100.0:
65 raise argparse.ArgumentTypeError(
66 "%s not in range [0.0, 100.0]" % pvalue)
71 """ Read the arguments, Invoke Test and Return the results"""
72 parser = argparse.ArgumentParser()
74 required_named = parser.add_argument_group("required named arguments")
75 required_named.add_argument("--lab_server_addr",
77 help=("The IP address of the "
78 "Spirent Lab Server"),
79 dest="lab_server_addr")
80 required_named.add_argument("--license_server_addr",
82 help=("The IP address of the Spirent "
84 dest="license_server_addr")
85 required_named.add_argument("--location_list",
87 help=("A comma-delimited list of test port "
91 optional_named = parser.add_argument_group("optional named arguments")
92 optional_named.add_argument("--metric",
94 help=("One among - Forwarding,\
95 Address Caching and Congestion"),
96 choices=["forwarding", "caching",
100 optional_named.add_argument("--test_session_name",
102 default="Rfc2889Ses",
103 help=("The friendly name to identify "
104 "the Spirent Lab Server test session"),
105 dest="test_session_name")
107 optional_named.add_argument("--test_user_name",
109 default="Rfc2889Usr",
110 help=("The friendly name to identify the "
111 "Spirent Lab Server test user"),
112 dest="test_user_name")
113 optional_named.add_argument("--results_dir",
116 help="The directory to copy results to",
118 optional_named.add_argument("--csv_results_file_prefix",
120 default="Rfc2889MaxFor",
121 help="The prefix for the CSV results files",
122 dest="csv_results_file_prefix")
123 optional_named.add_argument("--num_trials",
127 help=("The number of trials to execute during "
130 optional_named.add_argument("--trial_duration_sec",
134 help=("The duration of each trial executed "
136 dest="trial_duration_sec")
137 optional_named.add_argument("--traffic_pattern",
139 choices=["BACKBONE", "MESH", "PAIR"],
141 help="The traffic pattern between endpoints",
142 dest="traffic_pattern")
143 optional_named.add_argument("--frame_size_list",
144 type=lambda s: [int(item)
145 for item in s.split(',')],
148 help="A comma-delimited list of frame sizes",
149 dest="frame_size_list")
150 parser.add_argument("-v",
154 help="More output during operation when present",
157 args = parser.parse_args()
160 logger.debug("Creating results directory")
161 create_dir(args.results_dir)
162 locationList = [str(item) for item in args.location_list.split(',')]
164 session_name = args.test_session_name
165 user_name = args.test_user_name
168 # Load Spirent REST Library
169 from stcrestclient import stchttp
171 stc = stchttp.StcHttp(args.lab_server_addr)
172 session_id = stc.new_session(user_name, session_name)
173 stc.join_session(session_id)
174 except RuntimeError as e:
178 # Retrieve and display the server information
180 logger.debug("SpirentTestCenter system version: %s",
181 stc.get("system1", "version"))
185 logger.debug("Bring up license server")
186 license_mgr = stc.get("system1", "children-licenseservermanager")
188 logger.debug("license_mgr = %s", license_mgr)
189 stc.create("LicenseServer", under=license_mgr, attributes={
190 "server": args.license_server_addr})
192 # Create the root project object
194 logger.debug("Creating project ...")
195 project = stc.get("System1", "children-Project")
199 logger.debug("Creating ports ...")
201 for location in locationList:
202 stc.perform("CreateAndReservePorts", params={"locationList":
207 port_list_get = stc.get("System1.project", "children-port")
210 logger.debug("Adding Host Gen PArams")
211 gen_params = stc.create("EmulatedDeviceGenParams",
213 attributes={"Port": port_list_get})
215 # Create the DeviceGenEthIIIfParams object
216 stc.create("DeviceGenEthIIIfParams",
218 # Configuring Ipv4 interfaces
219 stc.create("DeviceGenIpv4IfParams",
222 stc.perform("DeviceGenConfigExpand",
223 params={"DeleteExisting": "No",
224 "GenParams": gen_params})
227 logger.debug("Set up the RFC2889 Forwarding test...")
228 stc.perform("Rfc2889SetupMaxForwardingRateTestCommand",
229 params={"Duration": args.trial_duration_sec,
230 "FrameSizeList": args.frame_size_list,
231 "NumOfTrials": args.num_trials,
232 "TrafficPattern": args.traffic_pattern})
234 # Save the configuration
235 stc.perform("SaveToTcc", params={"Filename": "2889.tcc"})
236 # Connect to the hardware...
237 stc.perform("AttachPorts", params={"portList": stc.get(
238 "system1.project", "children-port"), "autoConnect": "TRUE"})
239 # Apply configuration.
241 logger.debug("Apply configuration...")
245 logger.debug("Starting the sequencer...")
246 stc.perform("SequencerStart")
248 # Wait for sequencer to finish
250 "Starting test... Please wait for the test to complete...")
251 stc.wait_until_complete()
252 logger.info("The test has completed... Saving results...")
254 # Determine what the results database filename is...
255 lab_server_resultsdb = stc.get(
256 "system1.project.TestResultSetting", "CurrentResultFileName")
259 logger.debug("The lab server results database is %s",
260 lab_server_resultsdb)
262 stc.perform("CSSynchronizeFiles",
263 params={"DefaultDownloadDir": args.results_dir})
265 resultsdb = args.results_dir + \
266 lab_server_resultsdb.split("/Results")[1]
268 if not os.path.exists(resultsdb):
269 resultsdb = lab_server_resultsdb
270 logger.info("Failed to create the local summary DB file, using"
271 " the remote DB file instead.")
274 "The local summary DB file has been saved to %s", resultsdb)
277 stc.perform("QueryResult",
279 "DatabaseConnectionString":
282 ("RFC2889MaxForwardingRateTestResultDetailed"
285 logger.debug("resultsdict[\"Columns\"]: %s",
286 resultsdict["Columns"])
287 logger.debug("resultsdict[\"Output\"]: %s", resultsdict["Output"])
288 logger.debug("Result paths: %s",
289 stc.perform("GetTestResultSettingPaths"))
291 # Write results to csv
293 logger.debug("Writing CSV file to results directory %s",
295 write_query_results_to_csv(
296 args.results_dir, args.csv_results_file_prefix, resultsdict)
298 except RuntimeError as err:
302 logger.debug("Destroy session on lab server")
306 logger.info("Test complete!")
308 if __name__ == "__main__":