1 # Copyright (c) 2016-2017 Intel Corporation
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.
21 libs = subprocess.check_output(
22 'python -c "import site; print(site.getsitepackages())"', shell=True)
24 sys.path.extend(libs[1:-1].replace("'", "").split(','))
25 except subprocess.CalledProcessError:
28 # ixload uses its own py2. So importing jsonutils fails. So adding below
29 # workaround to support call from yardstick
31 from oslo_serialization import jsonutils
33 import json as jsonutils
35 from yardstick.common import exceptions #pylint: disable=wrong-import-position
38 from IxLoad import IxLoad, StatCollectorUtils
40 IxLoad = exceptions.ErrorClass
41 StatCollectorUtils = exceptions.ErrorClass
44 LOG = logging.getLogger(__name__)
45 CSV_FILEPATH_NAME = 'IxL_statResults.csv'
50 'L2-3 Stats for Client Ports.csv',
51 'L2-3 Stats for Server Ports.csv',
52 'IxLoad Detailed Report.html',
53 'IxLoad Detailed Report.pdf'
57 ["HTTP Client", "TCP Connections Established", "kSum"],
58 ["HTTP Client", "TCP Connection Requests Failed", "kSum"],
59 ["HTTP Client", "HTTP Simulated Users", "kSum"],
60 ["HTTP Client", "HTTP Concurrent Connections", "kSum"],
61 ["HTTP Client", "HTTP Connections", "kSum"],
62 ["HTTP Client", "HTTP Transactions", "kSum"],
63 ["HTTP Client", "HTTP Connection Attempts", "kSum"]
67 ["HTTP Server", "TCP Connections Established", "kSum"],
68 ["HTTP Server", "TCP Connection Requests Failed", "kSum"]
72 INCOMING_STAT_RECORD_TEMPLATE = """
73 =====================================
74 INCOMING STAT RECORD >>> %s
78 =====================================
81 INCOMING_STAT_INTERVAL_TEMPLATE = """
82 =====================================
83 Incoming stats: Time interval: %s
84 Incoming stats: Time interval: %s
85 =====================================
89 def validate_non_string_sequence(value, default=None, raise_exc=None):
90 if isinstance(value, collections.Sequence) and not isinstance(value, str):
93 raise raise_exc # pylint: disable=raising-bad-type
97 def join_non_strings(separator, *non_strings):
99 non_strings = validate_non_string_sequence(non_strings[0], raise_exc=RuntimeError)
100 except (IndexError, RuntimeError):
102 return str(separator).join(str(non_string) for non_string in non_strings)
105 class IXLOADHttpTest(object):
107 def __init__(self, test_input):
109 self.stat_utils = None
110 self.remote_server = None
111 self.config_file = None
112 self.results_on_windows = None
113 self.result_dir = None
116 self.ports_to_reassign = None
117 self.links_param = None
118 self.test_input = jsonutils.loads(test_input)
119 self.parse_run_test()
123 def format_ports_for_reassignment(ports):
124 formatted = [join_non_strings(';', p) for p in ports if len(p) == 3]
125 LOG.debug('for client ports:%s', os.linesep.join(formatted))
128 def reassign_ports(self, test, repository, ports_to_reassign):
129 LOG.debug('ReassignPorts: %s %s', test, repository)
131 chassis_chain = repository.cget('chassisChain')
132 LOG.debug('chassischain: %s', chassis_chain)
133 client_ports = ports_to_reassign[0::2]
134 server_ports = ports_to_reassign[1::2]
136 client_ports = self.format_ports_for_reassignment(client_ports)
137 LOG.debug('Reassigning client ports: %s', client_ports)
138 server_ports = self.format_ports_for_reassignment(server_ports)
139 LOG.debug('Reassigning server ports: %s', server_ports)
140 ports_to_set = client_ports + server_ports
143 LOG.debug('Reassigning ports: %s', ports_to_set)
144 test.setPorts(ports_to_set)
146 LOG.error('Error: Could not remap port assignment for: %s',
148 self.ix_load.delete(repository)
149 self.ix_load.disconnect()
153 def stat_collector(*args):
154 LOG.debug(INCOMING_STAT_RECORD_TEMPLATE, args, len(args), args[0], args[1])
157 def IxL_StatCollectorCommand(*args):
159 timestamp = args[1][1]
160 LOG.debug(INCOMING_STAT_INTERVAL_TEMPLATE, timestamp, stats)
163 def set_results_dir(test_controller, results_on_windows):
165 If the folder doesn't exists on the Windows Client PC,
166 IxLoad will automatically create it.
169 test_controller.setResultDir(results_on_windows)
171 LOG.error('Error creating results dir on Win: %s',
175 def load_config_file(self, config_file):
177 LOG.debug(config_file)
178 repository = self.ix_load.new("ixRepository", name=config_file)
181 LOG.error('Error: IxLoad config file not found: %s', config_file)
184 def update_network_address(self, net_traffic, address, gateway, prefix):
185 """Update ip address and gateway for net_traffic object
187 This function update field which configure source addresses for
188 traffic which is described by net_traffic object.
189 Do not return anything
191 :param net_traffic: (IxLoadObjectProxy) proxy obj to tcl net_traffic object
192 :param address: (str) Ipv4 range start address
193 :param gateway: (str) Ipv4 address of gateway
194 :param prefix: (int) subnet prefix
198 ethernet = net_traffic.network.getL1Plugin()
199 ix_net_l2_ethernet_plugin = ethernet.childrenList[0]
200 ix_net_ip_v4_v6_plugin = ix_net_l2_ethernet_plugin.childrenList[0]
201 ix_net_ip_v4_v6_range = ix_net_ip_v4_v6_plugin.rangeList[0]
203 ix_net_ip_v4_v6_range.config(
206 gatewayAddress=gateway)
208 raise exceptions.InvalidRxfFile
210 def update_network_mac_address(self, net_traffic, mac):
211 """Update MACaddress for net_traffic object
213 This function update field which configure MACaddresses for
214 traffic which is described by net_traffic object.
215 If mac == "auto" then will be configured auto generated mac
216 Do not return anything.
218 :param net_traffic: (IxLoadObjectProxy) proxy obj to tcl net_traffic object
219 :param mac: (str) MAC
223 ethernet = net_traffic.network.getL1Plugin()
224 ix_net_l2_ethernet_plugin = ethernet.childrenList[0]
225 ix_net_ip_v4_v6_plugin = ix_net_l2_ethernet_plugin.childrenList[0]
226 ix_net_ip_v4_v6_range = ix_net_ip_v4_v6_plugin.rangeList[0]
228 if str(mac).lower() == "auto":
229 ix_net_ip_v4_v6_range.config(autoMacGeneration=True)
231 ix_net_ip_v4_v6_range.config(autoMacGeneration=False)
232 mac_range = ix_net_ip_v4_v6_range.getLowerRelatedRange(
234 mac_range.config(mac=mac)
236 raise exceptions.InvalidRxfFile
238 def update_network_param(self, net_traffic, param):
239 """Update net_traffic by parameters specified in param"""
241 self.update_network_address(net_traffic, param["address"],
242 param["gateway"], param["subnet_prefix"])
244 self.update_network_mac_address(net_traffic, param["mac"])
246 def update_config(self):
247 """Update some fields by parameters from traffic profile"""
250 # self.test.communityList is a IxLoadObjectProxy to some tcl object
251 # which contain all net_traffic objects in scenario.
252 # net_traffic item has a name in format "activity_name@item_name"
254 for item in self.test.communityList:
255 net_traffics[item.name.split('@')[1]] = item
256 except Exception: # pylint: disable=broad-except
259 for name, net_traffic in net_traffics.items():
261 param = self.links_param[name]
263 LOG.debug('There is no param for net_traffic %s', name)
266 self.update_network_param(net_traffic, param["ip"])
268 def start_http_test(self):
269 self.ix_load = IxLoad()
271 LOG.debug('--- ixLoad obj: %s', self.ix_load)
273 self.ix_load.connect(self.remote_server)
277 log_tag = "IxLoad-api"
279 logger = self.ix_load.new("ixLogger", log_tag, 1)
280 log_engine = logger.getEngine()
281 log_engine.setLevels(self.ix_load.ixLogger.kLevelDebug,
282 self.ix_load.ixLogger.kLevelInfo)
283 log_engine.setFile(log_name, 2, 256, 1)
285 # Initialize stat collection utilities
286 self.stat_utils = StatCollectorUtils()
288 test_controller = self.ix_load.new("ixTestController", outputDir=1)
290 repository = self.load_config_file(self.config_file)
292 # Get the first test on the testList
293 test_name = repository.testList[0].cget("name")
294 self.test = repository.testList.getItem(test_name)
296 self.set_results_dir(test_controller, self.results_on_windows)
298 self.test.config(statsRequired=1, enableResetPorts=1, csvInterval=2,
299 enableForceOwnership=True)
303 # ---- Remap ports ----
305 self.reassign_ports(self.test, repository, self.ports_to_reassign)
306 except Exception: # pylint: disable=broad-except
307 LOG.exception("Exception occurred during reassign_ports")
309 # -----------------------------------------------------------------------
310 # Set up stat Collection
311 # -----------------------------------------------------------------------
312 test_server_handle = test_controller.getTestServerHandle()
313 self.stat_utils.Initialize(test_server_handle)
315 # Clear any stats that may have been registered previously
316 self.stat_utils.ClearStats()
318 # Define the stats we would like to collect
319 self.stat_utils.AddStat(caption="Watch_Stat_1",
320 statSourceType="HTTP Client",
321 statName="TCP Connections Established",
322 aggregationType="kSum",
325 self.stat_utils.AddStat(caption="Watch_Stat_2",
326 statSourceType="HTTP Client",
327 statName="TCP Connection Requests Failed",
328 aggregationType="kSum",
331 self.stat_utils.AddStat(caption="Watch_Stat_3",
332 statSourceType="HTTP Server",
333 statName="TCP Connections Established",
334 aggregationType="kSum",
337 self.stat_utils.AddStat(caption="Watch_Stat_4",
338 statSourceType="HTTP Server",
339 statName="TCP Connection Requests Failed",
340 aggregationType="kSum",
343 self.stat_utils.StartCollector(self.IxL_StatCollectorCommand)
345 test_controller.run(self.test)
346 self.ix_load.waitForTestFinish()
348 test_controller.releaseConfigWaitFinish()
350 # Stop the collector (running in the tcl event loop)
351 self.stat_utils.StopCollector()
354 test_controller.generateReport(detailedReport=1, format="PDF;HTML")
355 test_controller.releaseConfigWaitFinish()
357 self.ix_load.delete(self.test)
358 self.ix_load.delete(test_controller)
359 self.ix_load.delete(logger)
360 self.ix_load.delete(log_engine)
362 LOG.debug('Retrieving CSV stats from Windows Client PC ...')
363 for stat_file in STATS_TO_GET:
364 enhanced_stat_file = stat_file.replace('-', '')
365 enhanced_stat_file = enhanced_stat_file.replace(' ', '_')
366 enhanced_stat_file = enhanced_stat_file.replace('__', '_')
368 LOG.debug('Getting csv stat file: %s', stat_file)
369 src_file = os.path.join(self.results_on_windows, stat_file)
370 dst_file = os.path.join(self.result_dir, '_'.join(['ixLoad', enhanced_stat_file]))
371 self.ix_load.retrieveFileCopy(src_file, dst_file)
373 self.ix_load.disconnect()
375 def parse_run_test(self):
376 self.remote_server = self.test_input["remote_server"]
377 LOG.debug("remote tcl server: %s", self.remote_server)
379 self.config_file = self.test_input["ixload_cfg"]
380 LOG.debug("ixload config: %s", self.remote_server)
382 self.results_on_windows = 'C:/Results'
383 self.result_dir = self.test_input["result_dir"]
384 self.chassis = self.test_input["ixia_chassis"]
385 LOG.debug("remote ixia chassis: %s", self.chassis)
387 self.card = self.test_input["IXIA"]["card"]
388 self.ports_to_reassign = [
389 [self.chassis, self.card, port] for port in
390 self.test_input["IXIA"]["ports"]
393 LOG.debug("Ports to be reassigned: %s", self.ports_to_reassign)
395 self.links_param = self.test_input["links_param"]
396 LOG.debug("Links param to be applied: %s", self.links_param)
400 # Get the args from cmdline and parse and run the test
401 test_input = "".join(args[1:])
403 ixload_obj = IXLOADHttpTest(test_input)
404 ixload_obj.start_http_test()
406 if __name__ == '__main__':
407 LOG.info("Start http_ixload test")