From: xinfengx <xinfengx.zhao@intel.com>
To: dts@dpdk.org
Cc: xinfengx <xinfengx.zhao@intel.com>
Subject: [dts] [next][PATCH V1 1/5] framework: modify dts framework to support python3
Date: Mon, 13 Jan 2020 06:18:27 +0800 [thread overview]
Message-ID: <20200112221831.12192-2-xinfengx.zhao@intel.com> (raw)
In-Reply-To: <20200112221831.12192-1-xinfengx.zhao@intel.com>
Signed-off-by: xinfengx <xinfengx.zhao@intel.com>
---
framework/checkCase.py | 40 +++++-----
framework/config.py | 48 +++++------
framework/crb.py | 10 +--
framework/debugger.py | 10 +--
framework/dts.py | 8 +-
framework/dut.py | 26 +++---
framework/etgen.py | 6 +-
framework/json_reporter.py | 2 +-
framework/logger.py | 11 ++-
framework/main.py | 8 +-
framework/multiple_vm.py | 3 +-
framework/packet.py | 61 +++++++-------
framework/pktgen.py | 14 ++--
framework/pktgen_base.py | 14 ++--
framework/pktgen_ixia.py | 36 ++++-----
framework/pktgen_trex.py | 34 ++++----
framework/plotgraph.py | 22 ++---
framework/plotting.py | 8 +-
framework/pmd_output.py | 4 +-
framework/qemu_kvm.py | 160 ++++++++++++++++++-------------------
framework/qemu_libvirt.py | 38 ++++-----
framework/rst.py | 6 +-
framework/serializer.py | 2 -
framework/settings.py | 16 ++--
framework/ssh_pexpect.py | 10 +--
framework/test_case.py | 18 ++---
framework/tester.py | 28 +++----
framework/texttable.py | 16 ++--
framework/utils.py | 10 +--
framework/virt_base.py | 40 +++++-----
framework/virt_common.py | 2 +-
framework/virt_dut.py | 12 +--
framework/virt_resource.py | 89 ++++++++++-----------
framework/virt_scene.py | 119 ++++++++++++++-------------
34 files changed, 461 insertions(+), 470 deletions(-)
diff --git a/framework/checkCase.py b/framework/checkCase.py
index 62f2643..3c1db99 100644
--- a/framework/checkCase.py
+++ b/framework/checkCase.py
@@ -26,12 +26,12 @@ class CheckCase(object):
try:
self.check_function_dict = json.load(open(filter_json_file), object_pairs_hook=collections.OrderedDict)
except:
- print RED("Can't load check list for test cases, all case will be taken as supported")
+ print(RED("Can't load check list for test cases, all case will be taken as supported"))
try:
self.support_function_dict = json.load(open(support_json_file), object_pairs_hook=collections.OrderedDict)
except:
- print RED("Can't load support list for test cases, all case will be taken as supported")
+ print(RED("Can't load support list for test cases, all case will be taken as supported"))
def check_dut(self, dut):
"""
@@ -83,16 +83,16 @@ class CheckCase(object):
self.comments = ""
if self.dut is None:
- print RED("No Dut assigned before case skip check")
+ print(RED("No Dut assigned before case skip check"))
return skip_flag
- if case_name in self.check_function_dict.keys():
+ if case_name in list(self.check_function_dict.keys()):
case_checks = self.check_function_dict[case_name]
# each case may have several checks
for case_check in case_checks:
# init result for each check
skip_flag = False
- for key in case_check.keys():
+ for key in list(case_check.keys()):
# some items like "Bug ID" and "Comments" do not need check
try:
if 'Comments' == key:
@@ -101,7 +101,7 @@ class CheckCase(object):
continue
check_function = getattr(self, '_check_%s' % key.lower())
except:
- print RED("can't check %s type" % key)
+ print(RED("can't check %s type" % key))
# skip this check if any item not matched
if check_function(case_check[key]):
@@ -112,7 +112,7 @@ class CheckCase(object):
# if all items matched, this case should skip
if skip_flag:
- if 'Comments' in case_check.keys():
+ if 'Comments' in list(case_check.keys()):
self.comments = case_check['Comments']
return skip_flag
@@ -127,16 +127,16 @@ class CheckCase(object):
self.comments = ""
if self.dut is None:
- print RED("No Dut assigned before case support check")
+ print(RED("No Dut assigned before case support check"))
return support_flag
- if case_name in self.support_function_dict.keys():
+ if case_name in list(self.support_function_dict.keys()):
# each case may have several supports
case_supports = self.support_function_dict[case_name]
for case_support in case_supports:
# init result for each check
support_flag = True
- for key in case_support.keys():
+ for key in list(case_support.keys()):
# some items like "Bug ID" and "Comments" do not need check
try:
if 'Comments' == key:
@@ -145,7 +145,7 @@ class CheckCase(object):
continue
check_function = getattr(self, '_check_%s' % key.lower())
except:
- print RED("can't check %s type" % key)
+ print(RED("can't check %s type" % key))
# skip this case if any item not matched
if check_function(case_support[key]):
@@ -155,7 +155,7 @@ class CheckCase(object):
break
if support_flag is False:
- if 'Comments' in case_support.keys():
+ if 'Comments' in list(case_support.keys()):
self.comments = case_support['Comments']
return support_flag
@@ -184,14 +184,14 @@ if __name__ == "__main__":
# check dut
case_inst.check_dut(dut)
- print case_inst.case_skip("fdir_flexword_drop_ipv4")
- print case_inst.comments
- print case_inst.case_support("Vxlan_tunnel")
- print case_inst.comments
+ print(case_inst.case_skip("fdir_flexword_drop_ipv4"))
+ print(case_inst.comments)
+ print(case_inst.case_support("Vxlan_tunnel"))
+ print(case_inst.comments)
# check other dut
case_inst.check_dut(dut1)
- print case_inst.case_skip("fdir_flexword_drop_ipv4")
- print case_inst.comments
- print case_inst.case_support("Vxlan_tunnel")
- print case_inst.comments
+ print(case_inst.case_skip("fdir_flexword_drop_ipv4"))
+ print(case_inst.comments)
+ print(case_inst.case_support("Vxlan_tunnel"))
+ print(case_inst.comments)
diff --git a/framework/config.py b/framework/config.py
index 4b6c2ba..4dc3f31 100644
--- a/framework/config.py
+++ b/framework/config.py
@@ -34,7 +34,7 @@ Generic port and crbs configuration file load function
"""
import os
import re
-import ConfigParser # config parse module
+import configparser # config parse module
import argparse # parse arguments module
from settings import (IXIA, PKTGEN, PKTGEN_DPDK, PKTGEN_TREX, PKTGEN_IXIA,
CONFIG_ROOT_PATH, SUITE_SECTION_NAME)
@@ -53,7 +53,7 @@ GLOBALCONF = "%s/global_suite.cfg" % CONFIG_ROOT_PATH
class UserConf():
def __init__(self, config):
- self.conf = ConfigParser.SafeConfigParser()
+ self.conf = configparser.SafeConfigParser()
load_files = self.conf.read(config)
if load_files == []:
self.conf = None
@@ -107,7 +107,7 @@ class GlobalConf(UserConf):
try:
section_confs = self.global_conf.load_section(section_name)
except:
- print "FAILED FIND SECTION[%s] CONFIG!!!" % section_name
+ print("FAILED FIND SECTION[%s] CONFIG!!!" % section_name)
return global_cfg
if section_confs is None:
@@ -138,14 +138,14 @@ class SuiteConf(UserConf):
try:
case_confs = self.suite_conf.load_section(case_name)
except:
- print "FAILED FIND CASE[%s] CONFIG!!!" % case_name
+ print("FAILED FIND CASE[%s] CONFIG!!!" % case_name)
return case_cfg
if case_confs is None:
return case_cfg
conf = dict(case_confs)
- for key, data_string in conf.items():
+ for key, data_string in list(conf.items()):
case_cfg[key] = eval(data_string)
return case_cfg
@@ -179,7 +179,7 @@ class VirtConf(UserConf):
try:
virt_confs = self.virt_conf.load_section(name)
except:
- print "FAILED FIND SECTION %s!!!" % name
+ print("FAILED FIND SECTION %s!!!" % name)
return
for virt_conf in virt_confs:
@@ -228,7 +228,7 @@ class PortConf(UserConf):
# port config for vm in virtualization scenario
if 'dev_idx' in port_param:
- keys = port_param.keys()
+ keys = list(port_param.keys())
keys.remove('dev_idx')
self.ports_cfg[port_param['dev_idx']] = {
key: port_param[key] for key in keys}
@@ -236,14 +236,14 @@ class PortConf(UserConf):
# check pci BDF validity
if 'pci' not in port_param:
- print "NOT FOUND CONFIG FOR NO PCI ADDRESS!!!"
+ print("NOT FOUND CONFIG FOR NO PCI ADDRESS!!!")
continue
m = re.match(self.pci_regex, port_param['pci'])
if m is None:
- print "INVALID CONFIG FOR NO PCI ADDRESS!!!"
+ print("INVALID CONFIG FOR NO PCI ADDRESS!!!")
continue
- keys = port_param.keys()
+ keys = list(port_param.keys())
keys.remove('pci')
self.ports_cfg[port_param['pci']] = {
key: port_param[key] for key in keys}
@@ -255,7 +255,7 @@ class PortConf(UserConf):
return self.ports_cfg
def check_port_available(self, pci_addr):
- if pci_addr in self.ports_cfg.keys():
+ if pci_addr in list(self.ports_cfg.keys()):
return True
else:
return False
@@ -377,13 +377,13 @@ class IxiaConf(UserConf):
ixia_group['enable_rsfec'] = value
if 'Version' not in ixia_group:
- print 'ixia configuration file request ixia_version option!!!'
+ print('ixia configuration file request ixia_version option!!!')
continue
if 'IP' not in ixia_group:
- print 'ixia configuration file request ixia_ip option!!!'
+ print('ixia configuration file request ixia_ip option!!!')
continue
if 'Ports' not in ixia_group:
- print 'ixia configuration file request ixia_ports option!!!'
+ print('ixia configuration file request ixia_ports option!!!')
continue
self.ixia_cfg[group] = ixia_group
@@ -430,13 +430,13 @@ class PktgenConf(UserConf):
ixia_group['enable_rsfec'] = value
if 'Version' not in ixia_group:
- print 'ixia configuration file request ixia_version option!!!'
+ print('ixia configuration file request ixia_version option!!!')
return
if 'IP' not in ixia_group:
- print 'ixia configuration file request ixia_ip option!!!'
+ print('ixia configuration file request ixia_ip option!!!')
return
if 'Ports' not in ixia_group:
- print 'ixia configuration file request ixia_ports option!!!'
+ print('ixia configuration file request ixia_ports option!!!')
return
self.pktgen_cfg[section.lower()] = ixia_group
@@ -485,7 +485,7 @@ if __name__ == '__main__':
try:
VirtConf('/tmp/not-existed.cfg')
except VirtConfigParseException:
- print "Capture config parse failure"
+ print("Capture config parse failure")
# example for basic use configuration file
conf = UserConf(PORTCONF)
@@ -499,23 +499,23 @@ if __name__ == '__main__':
# example for port configuration file
portconf = PortConf(PORTCONF)
portconf.load_ports_config('DUT IP')
- print portconf.get_ports_config()
+ print(portconf.get_ports_config())
portconf.check_port_available('86:00.0')
# example for global virtualization configuration file
virtconf = VirtConf(VIRTCONF)
virtconf.load_virt_config('LIBVIRT')
- print virtconf.get_virt_config()
+ print(virtconf.get_virt_config())
# example for crbs configuration file
crbsconf = CrbsConf(CRBCONF)
- print crbsconf.load_crbs_config()
+ print(crbsconf.load_crbs_config())
# example for ixia configuration file
ixiaconf = IxiaConf(IXIACONF)
- print ixiaconf.load_ixia_config()
+ print(ixiaconf.load_ixia_config())
# example for suite configure file
suiteconf = SuiteConf("suite_sample")
- print suiteconf.load_case_config("case1")
- print suiteconf.load_case_config("case2")
+ print(suiteconf.load_case_config("case1"))
+ print(suiteconf.load_case_config("case2"))
diff --git a/framework/crb.py b/framework/crb.py
index c1f2a1c..2d81550 100644
--- a/framework/crb.py
+++ b/framework/crb.py
@@ -292,14 +292,14 @@ class Crb(object):
if configed_pcis:
if 'tester' in str(self):
tester_pci_in_cfg = []
- for item in configed_pcis.values():
+ for item in list(configed_pcis.values()):
for pci_info in match:
if item['peer'] == pci_info[0]:
tester_pci_in_cfg.append(pci_info)
match = tester_pci_in_cfg[:]
else:
dut_pci_in_cfg = []
- for key in configed_pcis.keys():
+ for key in list(configed_pcis.keys()):
for pci_info in match:
if key == pci_info[0]:
dut_pci_in_cfg.append(pci_info)
@@ -621,7 +621,7 @@ class Crb(object):
for line in cpuinfo:
(thread, core, socket, node) = line.split(',')[0:4]
- if core not in coremap.keys():
+ if core not in list(coremap.keys()):
coremap[core] = core_id
core_id += 1
@@ -691,7 +691,7 @@ class Crb(object):
self.reserved_cores = self.remove_reserved_cores(partial_cores, rsv_list)
# return thread list
- return map(str, thread_list)
+ return list(map(str, thread_list))
def get_core_list(self, config, socket=-1, from_last = False):
"""
@@ -798,7 +798,7 @@ class Crb(object):
temp.extend(thread_list)
thread_list = temp
i += 1
- return map(str, thread_list)
+ return list(map(str, thread_list))
def get_lcore_id(self, config, inverse = False):
"""
diff --git a/framework/debugger.py b/framework/debugger.py
index 937975c..3795f89 100644
--- a/framework/debugger.py
+++ b/framework/debugger.py
@@ -61,7 +61,7 @@ def list_command():
index = 0
from ssh_connection import CONNECTIONS
for connection in CONNECTIONS:
- for name, session in connection.items():
+ for name, session in list(connection.items()):
console.push('print \'connect %d: %10s\'' % (index, name))
index += 1
@@ -72,14 +72,14 @@ def connect_command(connect):
"""
from ssh_connection import CONNECTIONS
if type(connect) == int:
- name, session = CONNECTIONS[connect].items()[0]
- print GREEN("Connecting to session[%s]" % name)
+ name, session = list(CONNECTIONS[connect].items())[0]
+ print(GREEN("Connecting to session[%s]" % name))
session.session.interact()
else:
for connection in CONNECTIONS:
- for name, session in connection.items():
+ for name, session in list(connection.items()):
if name == connect:
- print GREEN("Connecting to session[%s]" % name)
+ print(GREEN("Connecting to session[%s]" % name))
session.session.interact()
diff --git a/framework/dts.py b/framework/dts.py
index 634a569..63d9464 100644
--- a/framework/dts.py
+++ b/framework/dts.py
@@ -30,7 +30,7 @@
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import re # regular expressions module
-import ConfigParser # config parse module
+import configparser # config parse module
import os # operation system module
import texttable # text format
import traceback # exception traceback
@@ -60,8 +60,8 @@ from config import CrbsConf
from checkCase import CheckCase
from utils import get_subclasses, copy_instance_attr, create_parallel_locks
import sys
-reload(sys)
-sys.setdefaultencoding('UTF8')
+import imp
+imp.reload(sys)
requested_tests = None
result = None
@@ -515,7 +515,7 @@ def run_all(config_file, pkgName, git, patch, skip_setup,
if dts_cfg_folder != '':
config_file = dts_cfg_folder + os.sep + config_file
- config = ConfigParser.SafeConfigParser()
+ config = configparser.SafeConfigParser()
load_cfg = config.read(config_file)
if len(load_cfg) == 0:
raise ConfigParseException(config_file)
diff --git a/framework/dut.py b/framework/dut.py
index 5409b93..7dea215 100644
--- a/framework/dut.py
+++ b/framework/dut.py
@@ -119,7 +119,7 @@ class Dut(Crb):
os_type = self.get_os_type()
if config:
# deal with cores
- if config.has_key('cores'):
+ if 'cores' in config:
if type(config['cores']) == list:
core_list = config['cores']
elif isinstance(config['cores'], str):
@@ -132,16 +132,16 @@ class Dut(Crb):
# deal with ports
w_pci_list = []
- if config.has_key('ports') and len(config['ports']) != 0:
+ if 'ports' in config and len(config['ports']) != 0:
for port in config['ports']:
if type(port) == int:
- if config.has_key('port_options') and port in config['port_options'].keys():
+ if 'port_options' in config and port in list(config['port_options'].keys()):
port_option = config['port_options'][port]
w_pci_list.append('-w %s,%s' % (self.ports_info[port]['pci'], port_option))
else:
w_pci_list.append('-w %s' % self.ports_info[port]['pci'])
else:
- if config.has_key('port_options') and port in config['port_options'].keys():
+ if 'port_options' in config and port in list(config['port_options'].keys()):
port_option = config['port_options'][port]
w_pci_list.append('-w %s,%s' % (port, port_option))
else:
@@ -150,7 +150,7 @@ class Dut(Crb):
# deal with black ports
b_pci_list = []
- if config.has_key('b_ports') and len(config['b_ports']) != 0:
+ if 'b_ports' in config and len(config['b_ports']) != 0:
for port in config['b_ports']:
if type(port) == int:
b_pci_list.append('-b %s' % self.ports_info[port]['pci'])
@@ -159,7 +159,7 @@ class Dut(Crb):
b_ports_str = ' '.join(b_pci_list)
# deal with no-pci
- if config.has_key('no_pci'):
+ if 'no_pci' in config:
if config['no_pci'] == True:
no_pci = '--no-pci'
else:
@@ -168,7 +168,7 @@ class Dut(Crb):
no_pci = ''
# deal with file prefix
- if config.has_key('prefix') and config['prefix'] != '':
+ if 'prefix' in config and config['prefix'] != '':
if fixed_prefix == True:
file_prefix = config['prefix']
else:
@@ -178,7 +178,7 @@ class Dut(Crb):
self.prefix_list.append(file_prefix)
# deal with vdev
- if config.has_key('vdevs') and len(config['vdevs']) != 0:
+ if 'vdevs' in config and len(config['vdevs']) != 0:
vdev = '--vdev ' + ' --vdev '.join(config['vdevs'])
else:
vdev = ''
@@ -190,7 +190,7 @@ class Dut(Crb):
+ blank + b_ports_str \
+ blank + no_pci \
+ blank + vdev
- self.prefix_list = []
+ self.prefix_list = []
else:
eal_str = '-l ' + ','.join(map(str, core_list)) \
+ blank + '-n %d' % self.get_memory_channels() \
@@ -215,7 +215,7 @@ class Dut(Crb):
eal_str = '-l ' + ','.join(map(str, core_list)) \
+ blank + '-n %d' % self.get_memory_channels() \
+ blank + pci_str
- self.prefix_list = []
+ self.prefix_list = []
else:
eal_str = '-l ' + ','.join(map(str, core_list)) \
+ blank + '-n %d' % self.get_memory_channels() \
@@ -786,7 +786,7 @@ class Dut(Crb):
elif self.nic_type == 'cfg':
if self.conf.check_port_available(pci_bus) is True:
return True
- elif self.nic_type not in NICS.keys():
+ elif self.nic_type not in list(NICS.keys()):
self.logger.warning("NOT SUPPORTED NIC TYPE: %s" % self.nic_type)
else:
codename = NICS[self.nic_type]
@@ -871,7 +871,7 @@ class Dut(Crb):
cached_ports_info = []
for port in self.ports_info:
port_info = {}
- for key in port.keys():
+ for key in list(port.keys()):
if type(port[key]) is str:
port_info[key] = port[key]
cached_ports_info.append(port_info)
@@ -1170,7 +1170,7 @@ class Dut(Crb):
# skip ping those not connected port
ipv6 = self.get_ipv6_address(dutPort)
if ipv6 == "Not connected":
- if self.tester.ports_info[remotePort].has_key('ipv4'):
+ if 'ipv4' in self.tester.ports_info[remotePort]:
out = self.tester.send_ping(
dutPort, self.tester.ports_info[remotePort]['ipv4'],
self.get_mac_address(dutPort))
diff --git a/framework/etgen.py b/framework/etgen.py
index a47d8cd..5fa1a66 100644
--- a/framework/etgen.py
+++ b/framework/etgen.py
@@ -72,8 +72,8 @@ class SoftwarePacketGenerator():
# assign core for ports
map_cmd = ""
- port_index = range(len(ports))
- port_map = dict(zip(ports, port_index))
+ port_index = list(range(len(ports)))
+ port_map = dict(list(zip(ports, port_index)))
self.tester.init_reserved_core()
# reserve one core for master process
@@ -190,7 +190,7 @@ class IxiaPacketGenerator(SSHConnection):
self.ixiaVersion = ixiaPorts[ixiaRef]["Version"]
self.ports = ixiaPorts[ixiaRef]["Ports"]
- if ixiaPorts[ixiaRef].has_key('force100g'):
+ if 'force100g' in ixiaPorts[ixiaRef]:
self.enable100g = ixiaPorts[ixiaRef]['force100g']
else:
self.enable100g = 'disable'
diff --git a/framework/json_reporter.py b/framework/json_reporter.py
index 80b6b7e..1b15bbe 100644
--- a/framework/json_reporter.py
+++ b/framework/json_reporter.py
@@ -73,4 +73,4 @@ class JSONReporter(object):
for dut in result.all_duts():
result_map[dut] = self.__scan_dut(result, dut)
with open(self.filename, 'w') as outfile:
- json.dump(result_map, outfile, indent=4, separators=(',', ': '), encoding="utf-8", sort_keys=True)
+ json.dump(result_map, outfile, indent=4, separators=(',', ': '), sort_keys=True)
diff --git a/framework/logger.py b/framework/logger.py
index 32dd954..4600c5f 100644
--- a/framework/logger.py
+++ b/framework/logger.py
@@ -200,7 +200,6 @@ class DTSLOG(BaseLoggerAdapter):
def __init__(self, logger, crb="suite"):
global log_dir
filename = inspect.stack()[1][1][:-3]
- self.name = filename.split('/')[-1]
self.error_lvl = logging.ERROR
self.warn_lvl = logging.WARNING
@@ -406,7 +405,7 @@ class LogParser(object):
try:
self.log_handler = open(self.log_path, 'r')
except:
- print RED("Failed to logfile %s" % log_path)
+ print(RED("Failed to logfile %s" % log_path))
return None
self.suite_pattern = re.compile(_TESTSUITE_NAME_FORMAT_PATTERN)
@@ -421,7 +420,7 @@ class LogParser(object):
begin = 0
end = len(self.loglist)
for line in self.loglist:
- m = self.suite_pattern.match(line.values()[0])
+ m = self.suite_pattern.match(list(line.values())[0])
if m:
if suite_name is None:
begin = self.loglist.index(line)
@@ -429,7 +428,7 @@ class LogParser(object):
begin = self.loglist.index(line)
for line in self.loglist[begin:]:
- m = self.end_pattern.match(line.values()[0])
+ m = self.end_pattern.match(list(line.values())[0])
if m:
if suite_name is None:
end = self.loglist.index(line)
@@ -443,7 +442,7 @@ class LogParser(object):
end = len(self.loglist)
for line in self.loglist:
# only handle case log
- m = self.case_pattern.match(line.values()[0])
+ m = self.case_pattern.match(list(line.values())[0])
if m:
# not determine case will start from beginning
if case_name is None:
@@ -453,7 +452,7 @@ class LogParser(object):
begin = self.loglist.index(line)
for line in self.loglist[begin:]:
- m = self.result_pattern.match(line.values()[0])
+ m = self.result_pattern.match(list(line.values())[0])
if m:
# not determine case will stop to the end
if case_name is None:
diff --git a/framework/main.py b/framework/main.py
index 0da946f..b5e5952 100755
--- a/framework/main.py
+++ b/framework/main.py
@@ -1,4 +1,4 @@
-#!/usr/bin/python
+#!/usr/bin/python3
# BSD LICENSE
#
# Copyright(c) 2010-2014 Intel Corporation. All rights reserved.
@@ -57,12 +57,12 @@ def git_build_package(gitLabel, pkgName, depot="dep"):
if os.path.exists("%s/%s" % (depot, gitPrefix)) is True:
ret = os.system("cd %s/%s && git pull --force" % (depot, gitPrefix))
else:
- print "git clone %s %s/%s" % (gitURL, depot, gitPrefix)
+ print("git clone %s %s/%s" % (gitURL, depot, gitPrefix))
ret = os.system("git clone %s %s/%s" % (gitURL, depot, gitPrefix))
if ret is not 0:
raise EnvironmentError
- print "git archive --format=tar.gz --prefix=%s %s -o %s" % (gitPrefix, gitLabel, pkgName)
+ print("git archive --format=tar.gz --prefix=%s %s -o %s" % (gitPrefix, gitLabel, pkgName))
ret = os.system("cd %s/%s && git archive --format=tar.gz --prefix=%s/ %s -o ../%s"
% (depot, gitPrefix, gitPrefix, gitLabel, pkgName))
if ret is not 0:
@@ -158,7 +158,7 @@ if args.git is not None:
try:
git_build_package(args.git, os.path.split(args.snapshot)[1])
except Exception:
- print "FAILED TO PREPARE DPDK PACKAGE!!!"
+ print("FAILED TO PREPARE DPDK PACKAGE!!!")
sys.exit()
# Main program begins here
diff --git a/framework/multiple_vm.py b/framework/multiple_vm.py
index fdb5b3d..68d2f5e 100644
--- a/framework/multiple_vm.py
+++ b/framework/multiple_vm.py
@@ -1,4 +1,3 @@
-#!/usr/bin/python
import time
import re
import threadpool
@@ -151,7 +150,7 @@ class MultipleVM(object):
self.logger.debug("Parallel task start for DUT%d %s" % (dut_id, vm_name))
- combinations = zip(commands, expects, timeouts)
+ combinations = list(zip(commands, expects, timeouts))
for combine in combinations:
command, expect, timeout = combine
# timeout value need enlarge if vm number increased
diff --git a/framework/packet.py b/framework/packet.py
index 5e86d6d..9144731 100755
--- a/framework/packet.py
+++ b/framework/packet.py
@@ -1,4 +1,3 @@
-#!/usr/bin/python
# BSD LICENSE
#
# Copyright(c) 2010-2015 Intel Corporation. All rights reserved.
@@ -391,11 +390,11 @@ class Packet(object):
self.pkt_opts = options
self.pkt_layers = []
- if 'pkt_gen' in self.pkt_opts.keys():
+ if 'pkt_gen' in list(self.pkt_opts.keys()):
if self.pkt_opts['pkt_gen'] == 'scapy':
self.pktgen = scapy()
else:
- print "Not support other pktgen yet!!!"
+ print("Not support other pktgen yet!!!")
else:
self.pktgen = scapy()
@@ -419,10 +418,10 @@ class Packet(object):
"""
self.pkt_len = 64
self.pkt_type = "UDP"
- if 'pkt_type' in options.keys():
+ if 'pkt_type' in list(options.keys()):
self.pkt_type = options['pkt_type']
- if self.pkt_type in self.def_packet.keys():
+ if self.pkt_type in list(self.def_packet.keys()):
self.pkt_layers = self.def_packet[self.pkt_type]['layers']
self.pkt_cfgload = self.def_packet[self.pkt_type]['cfgload']
if "IPv6" in self.pkt_type:
@@ -430,7 +429,7 @@ class Packet(object):
else:
self._load_pkt_layers()
- if 'pkt_len' in options.keys():
+ if 'pkt_len' in list(options.keys()):
self.pkt_len = options['pkt_len']
self._load_assign_layers()
@@ -449,7 +448,7 @@ class Packet(object):
if hasattr(self, 'configured_layer_raw') is False and self.pkt_cfgload is True:
payload = []
raw_confs = {}
- if 'ran_payload' in self.pkt_opts.keys():
+ if 'ran_payload' in list(self.pkt_opts.keys()):
for loop in range(payload_len):
payload.append("%02x" % random.randrange(0, 255))
else:
@@ -516,14 +515,14 @@ class Packet(object):
try:
self.update_pkt_str(i)
except:
- print("warning: packet %s update failed" % i)
+ print(("warning: packet %s update failed" % i))
elif isinstance(i, dict):
try:
self.update_pkt_dict(i)
except:
- print("warning: packet %s update failed" % i)
+ print(("warning: packet %s update failed" % i))
else:
- print("packet {} is not acceptable".format(i))
+ print(("packet {} is not acceptable".format(i)))
def generate_random_pkts(self, dstmac=None, pktnum=100, random_type=None, ip_increase=True, random_payload=False,
options=None):
@@ -562,7 +561,7 @@ class Packet(object):
self.config_layer('tcp', {'src': 65535, 'dst': 65535})
if "UDP" in self.pkt_type:
self.config_layer('udp', {'src': 65535, 'dst': 65535})
- if options.has_key('layers_config'):
+ if 'layers_config' in options:
self.config_layers(options['layers_config'])
if dstmac:
self.config_layer('ether', {'dst': '%s' % dstmac})
@@ -667,9 +666,9 @@ class Packet(object):
if send_bg: # if send_bg create a new session to execute send action
session_prefix = 'scapy_bg_session'
scapy_session = crb.create_session(session_prefix + time_stamp)
- scapy_session.send_command('python %s' % crb.tmp_file + scapy_cmd)
+ scapy_session.send_command('python3 %s' % crb.tmp_file + scapy_cmd)
else:
- crb.send_expect('python %s' % crb.tmp_file + scapy_cmd, '# ', timeout=timeout)
+ crb.send_expect('python3 %s' % crb.tmp_file + scapy_cmd, '# ', timeout=timeout)
return crb.tmp_file + scapy_cmd
def send_pkt(self, crb, tx_port='', count=1, interval=0, timeout=15):
@@ -688,13 +687,13 @@ class Packet(object):
try:
pids.append(re.search('\d+', out).group())
except AttributeError as e:
- print(e, ' :%s not killed' % file)
+ print((e, ' :%s not killed' % file))
else:
out = crb.send_expect('ps -ef |grep %s|grep -v grep' % filenames, expected='# ')
try:
pids.append(re.search('\d+', out).group())
except AttributeError as e:
- print(e, ' :%s not killed' % filenames)
+ print((e, ' :%s not killed' % filenames))
pid = ' '.join(pids)
if pid:
crb.send_expect('kill -9 %s' % pid, expected='# ')
@@ -711,14 +710,14 @@ class Packet(object):
found = False
l_type = layer.lower()
- for types in LayersTypes.values():
+ for types in list(LayersTypes.values()):
if l_type in types:
found = True
break
if found is False:
self.pkt_layers.remove(l_type)
- print "INVAILD LAYER TYPE [%s]" % l_type.upper()
+ print("INVAILD LAYER TYPE [%s]" % l_type.upper())
def assign_layers(self, layers=None):
"""
@@ -732,14 +731,14 @@ class Packet(object):
found = False
l_type = layer.lower()
- for types in LayersTypes.values():
+ for types in list(LayersTypes.values()):
if l_type in types:
found = True
break
if found is False:
self.pkt_layers.remove(l_type)
- print "INVAILD LAYER TYPE [%s]" % l_type.upper()
+ print("INVAILD LAYER TYPE [%s]" % l_type.upper())
self.pktgen.add_layers(self.pkt_layers)
if layers:
@@ -775,7 +774,7 @@ class Packet(object):
self.pkt_layers = []
self.pkt_cfgload = True
for layer in layers:
- if layer in name2type.keys():
+ if layer in list(name2type.keys()):
self.pkt_layers.append(name2type[layer])
def config_def_layers(self):
@@ -826,7 +825,7 @@ class Packet(object):
try:
idx = self.pkt_layers.index(layer)
except Exception as e:
- print "INVALID LAYER ID %s" % layer
+ print("INVALID LAYER ID %s" % layer)
return False
if self.check_layer_config() is False:
@@ -849,10 +848,10 @@ class Packet(object):
for layer in layers:
name, config = layer
if name not in self.pkt_layers:
- print "[%s] is missing in packet!!!" % name
+ print("[%s] is missing in packet!!!" % name)
raise
if self.config_layer(name, config) is False:
- print "[%s] failed to configure!!!" % name
+ print("[%s] failed to configure!!!" % name)
raise
def strip_layer_element(self, layer, element, p_index=0):
@@ -926,13 +925,13 @@ def get_filter_cmd(filters=[]):
for pktfilter in filters:
filter_cmd = ""
if pktfilter['layer'] == 'ether':
- if pktfilter['config'].keys()[0] == 'dst':
+ if list(pktfilter['config'].keys())[0] == 'dst':
dmac = pktfilter['config']['dst']
filter_cmd = "ether dst %s" % dmac
- elif pktfilter['config'].keys()[0] == 'src':
+ elif list(pktfilter['config'].keys())[0] == 'src':
smac = pktfilter['config']['src']
filter_cmd = "ether src %s" % smac
- elif pktfilter['config'].keys()[0] == 'type':
+ elif list(pktfilter['config'].keys())[0] == 'type':
eth_type = pktfilter['config']['type']
eth_format = r"(\w+) (\w+)"
m = re.match(eth_format, eth_type)
@@ -945,14 +944,14 @@ def get_filter_cmd(filters=[]):
elif m.group(1) == 'not':
filter_cmd = 'ether[12:2] != %s' % type_hex
elif pktfilter['layer'] == 'network':
- if pktfilter['config'].keys()[0] == 'srcport':
+ if list(pktfilter['config'].keys())[0] == 'srcport':
sport = pktfilter['config']['srcport']
filter_cmd = "src port %s" % sport
- elif pktfilter['config'].keys()[0] == 'dstport':
+ elif list(pktfilter['config'].keys())[0] == 'dstport':
dport = pktfilter['config']['dstport']
filter_cmd = "dst port %s" % dport
elif pktfilter['layer'] == 'userdefined':
- if pktfilter['config'].keys()[0] == 'pcap-filter':
+ if list(pktfilter['config'].keys())[0] == 'pcap-filter':
filter_cmd = pktfilter['config']['pcap-filter']
if len(filter_cmds):
@@ -998,7 +997,7 @@ def start_tcpdump(crb, intf, count=0, filters=None, lldp_forbid=True):
param = "-P" + " in"
if len(param) == 0:
- print "tcpdump not support direction choice!!!"
+ print("tcpdump not support direction choice!!!")
if lldp_forbid and (LLDP_FILTER not in filters):
filters.append(LLDP_FILTER)
@@ -1027,7 +1026,7 @@ def stop_and_load_tcpdump_packets(index='', timeout=1):
"""
Stop sniffer and return packet object
"""
- if index in SNIFF_PIDS.keys():
+ if index in list(SNIFF_PIDS.keys()):
pipe, intf, filename = SNIFF_PIDS.pop(index)
pipe.get_session_before(timeout)
pipe.send_command('^C')
diff --git a/framework/pktgen.py b/framework/pktgen.py
index 7f8223f..889e94a 100644
--- a/framework/pktgen.py
+++ b/framework/pktgen.py
@@ -119,12 +119,12 @@ class PacketGeneratorHelper(object):
fields_config = {}
# set ethernet protocol layer fields
layer_name = 'mac'
- if layer_name in suite_config.keys() and \
+ if layer_name in list(suite_config.keys()) and \
'Ethernet' in self.packetLayers:
fields_config[layer_name] = {}
suite_fields = suite_config.get(layer_name)
pcap_fields = self.packetLayers.get('Ethernet')
- for name, config in suite_fields.iteritems():
+ for name, config in suite_fields.items():
action = config.get('action') or 'default'
range = config.get('range') or 64
step = config.get('step') or 1
@@ -137,12 +137,12 @@ class PacketGeneratorHelper(object):
fields_config[layer_name][name]['action'] = action
# set ip protocol layer fields
layer_name = 'ip'
- if layer_name in suite_config.keys() and \
+ if layer_name in list(suite_config.keys()) and \
'IP' in self.packetLayers:
fields_config[layer_name] = {}
suite_fields = suite_config.get(layer_name)
pcap_fields = self.packetLayers.get('IP')
- for name, config in suite_fields.iteritems():
+ for name, config in suite_fields.items():
action = config.get('action') or 'default'
range = config.get('range') or 64
step = config.get('step') or 1
@@ -155,14 +155,14 @@ class PacketGeneratorHelper(object):
fields_config[layer_name][name]['action'] = action
# set vlan protocol layer fields, only support one layer vlan here
layer_name = 'vlan'
- if layer_name in suite_config.keys() and \
+ if layer_name in list(suite_config.keys()) and \
'802.1Q' in self.packetLayers:
fields_config[layer_name] = {}
suite_fields = suite_config.get(layer_name)
pcap_fields = self.packetLayers.get('802.1Q')
# only support one layer vlan here, so set name to `0`
name = 0
- if name in suite_fields.keys():
+ if name in list(suite_fields.keys()):
config = suite_fields[name]
action = config.get('action') or 'default'
range = config.get('range') or 64
@@ -207,7 +207,7 @@ def getPacketGenerator(tester, pktgen_type=PKTGEN_IXIA):
PKTGEN_IXIA: IxiaPacketGenerator,
PKTGEN_TREX: TrexPacketGenerator,}
- if pktgen_type in pktgen_cls.keys():
+ if pktgen_type in list(pktgen_cls.keys()):
CLS = pktgen_cls.get(pktgen_type)
return CLS(tester)
else:
diff --git a/framework/pktgen_base.py b/framework/pktgen_base.py
index 5e51b1a..7e1ff48 100644
--- a/framework/pktgen_base.py
+++ b/framework/pktgen_base.py
@@ -226,7 +226,7 @@ class PacketGenerator(object):
If set this key value, pktgen will return several throughput statistic
data within a duration traffic. If not set this key value, only
return one statistic data. It is ignored by default.
-
+
callback:
this key works with ``interval`` key. If it is set, the callback
of suite level will be executed after getting throughput statistic.
@@ -306,7 +306,7 @@ class PacketGenerator(object):
result = self._measure_loss(stream_ids, options)
# here only to make sure that return value is the same as dts/etgen format
# In real testing scenario, this method can offer more data than it
- return result.values()[0]
+ return list(result.values())[0]
def measure_latency(self, stream_ids=[], options={}):
"""
@@ -352,7 +352,7 @@ class PacketGenerator(object):
support multiple link peer, if any link peer loss rate happen set
return value to False
'''
- for port_id, _result in result.iteritems():
+ for port_id, _result in result.items():
loss_rate, _, _ = _result
if loss_rate > permit_loss_rate:
return False
@@ -393,7 +393,7 @@ class PacketGenerator(object):
# return data is the same with dts/etgen format
# In fact, multiple link peer have multiple loss rate value,
# here only pick one
- tx_num, rx_num = result.values()[0][1:]
+ tx_num, rx_num = list(result.values())[0][1:]
return rate_percent, tx_num, rx_num
_options = deepcopy(options)
# if warm up option 'delay' is set, ignore it in next work flow
@@ -421,7 +421,7 @@ class PacketGenerator(object):
# here only pick one
last_result = loss_rate_table[-1]
rate_percent = last_result[0]
- tx_num, rx_num = last_result[1].values()[0][1:]
+ tx_num, rx_num = list(last_result[1].values())[0][1:]
return rate_percent, tx_num, rx_num
def measure_rfc2544_with_pps(self, stream_ids=[], options={}):
@@ -460,7 +460,7 @@ class PacketGenerator(object):
# use last result as return data to keep the same with dts/etgen format
# In fact, multiple link peer have multiple loss rate value,
# here only pick one
- return loss_pps_table[-1][1].values()[0]
+ return list(loss_pps_table[-1][1].values())[0]
def measure_rfc2544_dichotomy(self, stream_ids=[], options={}):
""" check loss rate using dichotomy algorithm
@@ -611,4 +611,4 @@ class PacketGenerator(object):
pass
-class DpdkPacketGenerator(PacketGenerator): pass # not implemented
\ No newline at end of file
+class DpdkPacketGenerator(PacketGenerator): pass # not implemented
diff --git a/framework/pktgen_ixia.py b/framework/pktgen_ixia.py
index 14b5d5b..94432a2 100644
--- a/framework/pktgen_ixia.py
+++ b/framework/pktgen_ixia.py
@@ -73,7 +73,7 @@ class Ixia(SSHConnection):
self.ixiaVersion = ixiaPorts[ixiaRef]["Version"]
self.ports = ixiaPorts[ixiaRef]["Ports"]
- if ixiaPorts[ixiaRef].has_key('force100g'):
+ if 'force100g' in ixiaPorts[ixiaRef]:
self.enable100g = ixiaPorts[ixiaRef]['force100g']
else:
self.enable100g = 'disable'
@@ -194,7 +194,7 @@ class Ixia(SSHConnection):
'default': 'idle'}
cmds = []
- for name, config in fields.iteritems():
+ for name, config in fields.items():
default_config = default_fields.get(name)
mac_start = config.get('start') or default_config.get('start')
mac_end = config.get('end')
@@ -229,7 +229,7 @@ class Ixia(SSHConnection):
default_fields.pop(name)
# if some filed not set, set it here
if default_fields:
- for name, config in default_fields.iteritems():
+ for name, config in default_fields.items():
ip_start = config.get('start')
prefix = 'sa' if name == 'src' else 'da'
cmds.append('stream config -{0} "{1}"'.format(prefix, ip_start))
@@ -274,7 +274,7 @@ class Ixia(SSHConnection):
# set default
'default': 'ipIdle',}
cmds = []
- for name, config in fields.iteritems():
+ for name, config in fields.items():
default_config = default_fields.get(name)
fv_name = 'IP.{0}'.format(name)
ip_start = config.get('start') or default_config.get('start')
@@ -291,7 +291,7 @@ class Ixia(SSHConnection):
mask = config.get('mask')
_step = config.get('step')
- step = int(_step) if _step and isinstance(_step, (str, unicode)) else \
+ step = int(_step) if _step and isinstance(_step, str) else \
_step or 1
action = config.get('action')
# get ixia command prefix
@@ -318,7 +318,7 @@ class Ixia(SSHConnection):
if not default_fields:
return cmds
# if some filed not set, set it here
- for name, config in default_fields.iteritems():
+ for name, config in default_fields.items():
ip_start = config.get('start')
prefix = 'source' if name == 'src' else 'dest'
cmds.append('ip config -{0}IpAddr "{1}"'.format(prefix, ip_start))
@@ -426,7 +426,7 @@ class Ixia(SSHConnection):
# No change to VlanID tag regardless of repeat
'idle': 'vIdle',}
cmds = []
- for name, config in fields.iteritems():
+ for name, config in fields.items():
fv_name = '8021Q.{0}'.format(name)
vlan_start = config.get('start') or 0
vlan_end = config.get('end') or 256
@@ -533,7 +533,7 @@ class Ixia(SSHConnection):
frameType = txmode.get('frameType') or {}
time_unit = frameType.get('type', 'ns')
gapUnit = gapUnits.get(time_unit) \
- if time_unit in gapUnits.keys() else gapUnits.get('ns')
+ if time_unit in list(gapUnits.keys()) else gapUnits.get('ns')
# The inter-stream gap is the delay in clock ticks between stream.
# This delay comes after the receive trigger is enabled. Setting this
# option to 0 means no delay. (default = 960.0)
@@ -879,14 +879,14 @@ class Ixia(SSHConnection):
# calculate total streams of ports
for (txPort, rxPort, pcapFile, option) in portList:
- if txPort not in self.stream_total.keys():
+ if txPort not in list(self.stream_total.keys()):
self.stream_total[txPort] = 1
else:
self.stream_total[txPort] += 1
# stream/flow setting
for (txPort, rxPort, pcapFile, option) in portList:
- if txPort not in self.stream_index.keys():
+ if txPort not in list(self.stream_index.keys()):
self.stream_index[txPort] = 1
frame_index = self.stream_index[txPort]
self.config_stream(pcapFile, option, txPort,
@@ -1346,7 +1346,7 @@ class Ixia(SSHConnection):
'throughput': self.get_throughput_stat,
'loss': self.get_loss_stat,
'latency': self.get_latency_stat,}
- if mode not in methods.keys():
+ if mode not in list(methods.keys()):
msg = "not support mode <{0}>".format(mode)
raise Exception(msg)
# get custom mode stat
@@ -1441,7 +1441,7 @@ class IxiaPacketGenerator(PacketGenerator):
'''
check if a pci address is managed by the packet generator
'''
- for name, _port_obj in self._conn.ports.iteritems():
+ for name, _port_obj in self._conn.ports.items():
_pci = _port_obj.info['pci_addr']
self.logger.debug((_pci, pci))
if _pci == pci:
@@ -1464,14 +1464,14 @@ class IxiaPacketGenerator(PacketGenerator):
return None
conf = {}
#get the subnet range of src and dst ip
- if self.conf.has_key("ip_src"):
+ if "ip_src" in self.conf:
conf['src'] = {}
ip_src = self.conf['ip_src']
ip_src_range = ip_src.split('-')
conf['src']['start'] = ip_src_range[0]
conf['src']['end'] = ip_src_range[1]
- if self.conf.has_key("ip_dst"):
+ if "ip_dst" in self.conf:
conf['dst'] = {}
ip_dst = self.conf['ip_dst']
ip_dst_range = ip_dst.split('-')
@@ -1557,7 +1557,7 @@ class IxiaPacketGenerator(PacketGenerator):
''' convert ixia loss rate statistics format to dts PacketGenerator format '''
# tx packet
port_id = stream.get("tx_port")
- if port_id in stats.keys():
+ if port_id in list(stats.keys()):
port_stats = stats[port_id]
else:
msg = "port {0} statistics is not found".format(port_id)
@@ -1578,7 +1578,7 @@ class IxiaPacketGenerator(PacketGenerator):
def _latency_stats(self, stream, stats):
''' convert ixia latency statistics format to dts PacketGenerator format '''
port_id = stream.get("tx_port")
- if port_id in stats.keys():
+ if port_id in list(stats.keys()):
port_stats = stats[port_id]
else:
msg = "port {0} latency stats is not found".format(port_id)
@@ -1619,7 +1619,7 @@ class IxiaPacketGenerator(PacketGenerator):
self._rx_ports.append(rx_port)
# set all streams in one port to do batch configuration
options = stream['options']
- if tx_port not in port_config.keys():
+ if tx_port not in list(port_config.keys()):
port_config[tx_port] = []
config = {}
config.update(options)
@@ -1641,7 +1641,7 @@ class IxiaPacketGenerator(PacketGenerator):
raise Exception(msg)
#-------------------------------------------------------------------
port_lists = []
- for port_id, option in port_config.iteritems():
+ for port_id, option in port_config.items():
port_lists += option
self._conn.clear_tcl_buffer()
rxPortlist, txPortlist = self._conn.prepare_port_list(
diff --git a/framework/pktgen_trex.py b/framework/pktgen_trex.py
index 61c8c0c..202c778 100644
--- a/framework/pktgen_trex.py
+++ b/framework/pktgen_trex.py
@@ -81,7 +81,7 @@ class TrexConfigVm(object):
_ip_start = self.ipv4_str_to_num(self.is_valid_ipv4_ret(ip_start))
_ip_end = self.ipv4_str_to_num(self.is_valid_ipv4_ret(ip_end))
_step = self.ipv4_str_to_num(self.is_valid_ipv4_ret(step)) \
- if isinstance(step, (str, unicode)) else step
+ if isinstance(step, str) else step
if mode == 'inc' or mode == 'dec':
min_value = _ip_start
max_value = _ip_end
@@ -110,7 +110,7 @@ class TrexConfigVm(object):
###################################################################
# mac inc/dec/random
if 'mac' in option:
- for name, config in option['mac'].iteritems():
+ for name, config in option['mac'].items():
mac_start = config.get('start') or '00:00:00:00:00:00'
mac_end = config.get('end') or 'FF:FF:FF:FF:FF:FF'
step = config.get('step') or 1
@@ -124,7 +124,7 @@ class TrexConfigVm(object):
###################################################################
# src ip mask inc/dec/random
if 'ip' in option:
- for name, config in option['ip'].iteritems():
+ for name, config in option['ip'].items():
ip_start = config.get('start') or '0.0.0.1'
ip_end = config.get('end') or '0.0.0.255'
step = config.get('step') or 1
@@ -139,7 +139,7 @@ class TrexConfigVm(object):
###################################################################
# src ip mask inc/dec/random
if 'port' in option:
- for name, config in option['port'].iteritems():
+ for name, config in option['port'].items():
protocol = config.get('protocol') or 'UDP'
port_start = config.get('start') or 1
port_end = config.get('end') or 255
@@ -158,7 +158,7 @@ class TrexConfigVm(object):
###################################################################
# vlan field inc/dec/random
if 'vlan' in option:
- for name, config in option['vlan'].iteritems():
+ for name, config in option['vlan'].items():
vlan_start = config.get('start') \
if config.get('start') != None else 0
vlan_end = config.get('end') or 256
@@ -237,7 +237,7 @@ class TrexConfigStream(object):
'max_value': 255,
'size': 4,
'step': 1}
- for name, value in default.iteritems():
+ for name, value in default.items():
if name not in config:
config[name] = value
@@ -248,7 +248,7 @@ class TrexConfigStream(object):
msg = "layer <{0}> field name <{1}> is not defined".format
fv_names = []
fix_chksum = False
- for layer, _config in configs.iteritems():
+ for layer, _config in configs.items():
# set default value
if isinstance(_config, (tuple, list)):
config = _config[0]
@@ -479,7 +479,7 @@ class TrexPacketGenerator(PacketGenerator):
'''
get port pci address
'''
- for name, _port_obj in self._conn.ports.iteritems():
+ for name, _port_obj in self._conn.ports.items():
if name == port_id:
_pci = _port_obj.info['pci_addr']
return _pci
@@ -490,7 +490,7 @@ class TrexPacketGenerator(PacketGenerator):
'''
get port management id of the packet generator
'''
- for name, _port_obj in self._conn.ports.iteritems():
+ for name, _port_obj in self._conn.ports.items():
_pci = _port_obj.info['pci_addr']
if _pci == pci:
return name
@@ -501,7 +501,7 @@ class TrexPacketGenerator(PacketGenerator):
'''
check if a pci address is managed by the packet generator
'''
- for name, _port_obj in self._conn.ports.iteritems():
+ for name, _port_obj in self._conn.ports.items():
_pci = _port_obj.info['pci_addr']
self.logger.debug((_pci, pci))
if _pci == pci:
@@ -584,7 +584,7 @@ class TrexPacketGenerator(PacketGenerator):
def _prepare_generator(self):
''' start trex server '''
- if self.conf.has_key('start_trex') and self.conf['start_trex']:
+ if 'start_trex' in self.conf and self.conf['start_trex']:
app_param_temp = "-i"
# flow control
flow_control = self.conf.get('flow_control')
@@ -612,14 +612,14 @@ class TrexPacketGenerator(PacketGenerator):
return None # close it and wait for more discussion about pktgen framework
conf = {}
#get the subnet range of src and dst ip
- if self.conf.has_key("ip_src"):
+ if "ip_src" in self.conf:
conf['src'] = {}
ip_src = self.conf['ip_src']
ip_src_range = ip_src.split('-')
conf['src']['start'] = ip_src_range[0]
conf['src']['end'] = ip_src_range[1]
- if self.conf.has_key("ip_dst"):
+ if "ip_dst" in self.conf:
conf['dst'] = {}
ip_dst = self.conf['ip_dst']
ip_dst_range = ip_dst.split('-')
@@ -701,7 +701,7 @@ class TrexPacketGenerator(PacketGenerator):
def _loss_rate_stats(self, stream, stats):
# tx packet
port_id = stream.get("tx_port")
- if port_id in stats.keys():
+ if port_id in list(stats.keys()):
port_stats = stats[port_id]
else:
msg = "port {0} statistics is not found".format(port_id)
@@ -722,7 +722,7 @@ class TrexPacketGenerator(PacketGenerator):
def _latency_stats(self, stream, stats):
_stats = stats.get('latency')
port_id = stream.get("tx_port")
- if port_id in _stats.keys():
+ if port_id in list(_stats.keys()):
port_stats = _stats[port_id]['latency']
else:
msg = "port {0} latency stats is not found".format(port_id)
@@ -751,7 +751,7 @@ class TrexPacketGenerator(PacketGenerator):
self._rx_ports.append(rx_port)
# set all streams in one port to do batch configuration
options = stream['options']
- if tx_port not in port_config.keys():
+ if tx_port not in list(port_config.keys()):
port_config[tx_port] = []
config = {}
config.update(options)
@@ -777,7 +777,7 @@ class TrexPacketGenerator(PacketGenerator):
self._conn.reset(ports=self._ports)
config_inst = TrexConfigStream()
- for port_id, config in port_config.iteritems():
+ for port_id, config in port_config.items():
# add a group of streams in one port
config_inst.add_streams(self._conn, config, ports=[port_id],
latency=latency)
diff --git a/framework/plotgraph.py b/framework/plotgraph.py
index 07e849b..56fd2b7 100644
--- a/framework/plotgraph.py
+++ b/framework/plotgraph.py
@@ -309,10 +309,10 @@ class Plot2DGraph:
currGraph.graphType = graphType
if len(xData) != len(yData):
- print 'Error xData = ' + str(len(xData))
- print 'yData = ' + str(len(yData))
- print xData
- print yData
+ print('Error xData = ' + str(len(xData)))
+ print('yData = ' + str(len(yData)))
+ print(xData)
+ print(yData)
return
currGraph.xs = xData
@@ -358,13 +358,13 @@ class Plot2DGraph:
ax.set_ylabel(graph.yLabel)
if graph.xticks:
- ax.set_xticks(range(len(graph.xticks)))
+ ax.set_xticks(list(range(len(graph.xticks))))
ax.set_xticklabels(graph.xticks)
elif self.xticklabels:
ax.set_xticks(self.xticks)
ax.set_xticklabels(self.xticklabels)
if graph.yticks:
- ax.set_yticks(range(len(graph.yticks)))
+ ax.set_yticks(list(range(len(graph.yticks))))
ax.set_yticklabels(graph.yticks)
elif self.yticklabels:
ax.set_yticks(self.yticks)
@@ -392,7 +392,7 @@ class Plot2DGraph:
# deprecated
if graph.expectedXs:
- print 'DEPRECATED'
+ print('DEPRECATED')
return
if graph.graphType and graph.graphType == 'bar':
@@ -420,7 +420,7 @@ class Plot2DGraph:
newAx.spines['left'].set_facecolor('r')
newAx.spines['left'].set_edgecolor('r')
- newAx.set_yticks(range(len(oldAx.get_yticks())))
+ newAx.set_yticks(list(range(len(oldAx.get_yticks()))))
newAx.set_yticklabels(self.newYticks[0:len(oldAx.get_yticks())])
newAx.set_ylabel(self.newYLabel, color='b')
newAx.yaxis.set_visible(True)
@@ -658,7 +658,7 @@ class Plot2DGraph:
# newAx.spines['bottom'].set_facecolor('red')
# newAx.spines['bottom'].set_edgecolor('red')
- newAx.set_xticks(range(len(self.newXticks)))
+ newAx.set_xticks(list(range(len(self.newXticks))))
newAx.set_xticklabels(self.newXticks)
newAx.set_xlabel(self.newXLabel, color='b')
newAx.xaxis.set_visible(True)
@@ -695,7 +695,7 @@ class Plot2DGraph:
newAx.spines['bottom'].set_facecolor('r')
newAx.spines['bottom'].set_edgecolor('r')
- newAx.set_xticks(range(len(self.newXticks)))
+ newAx.set_xticks(list(range(len(self.newXticks))))
newAx.set_xticklabels(self.newXticks)
newAx.set_xlabel(self.newXLabel, color='b')
newAx.xaxis.set_visible(True)
@@ -754,7 +754,7 @@ class Plot2DGraph:
"""check num subplots is not too much"""
if(self.numSubPlots > 4):
- print "Max subplots exceeded: " + str(self.numSubPlots)
+ print("Max subplots exceeded: " + str(self.numSubPlots))
return
# generate graphs, write to file
diff --git a/framework/plotting.py b/framework/plotting.py
index 9e0ae54..7d036fe 100644
--- a/framework/plotting.py
+++ b/framework/plotting.py
@@ -106,7 +106,7 @@ class Plotting(object):
for yseries in ydata:
if len(xdata) != len(yseries):
- print utils.RED("The number of items in X axis (%s) and Y axis (%s) does not match." % (xdata, ydata))
+ print(utils.RED("The number of items in X axis (%s) and Y axis (%s) does not match." % (xdata, ydata)))
return ''
image_path = "%s/%s.%s" % (self.plots_path, image_filename,
@@ -124,7 +124,7 @@ class Plotting(object):
pgraph.setBarLegends(0, legend)
# For each value in the x axis add corresponding bar (array in ydata)
- for xvalue in xrange(len(xdata)):
+ for xvalue in range(len(xdata)):
yvalues = [_[xvalue] for _ in ydata]
pgraph.addBarData(0, xdata[xvalue], yvalues)
@@ -166,7 +166,7 @@ class Plotting(object):
# workaround
if numPlots > len(line_colours):
- print 'WARNING - numPlots > len(line_colours)'
+ print('WARNING - numPlots > len(line_colours)')
r = 0x00
g = 0x66
b = 0xFF
@@ -191,7 +191,7 @@ class Plotting(object):
pgraph.setBarLegends(0, legend)
# For each value in the x axis add corresponding bar (array in ydata)
- for i in list(xrange(numPlots)):
+ for i in list(range(numPlots)):
yDataStart = i * numticks
pgraph.addPlotData(i, 'Number of active pipes per output port',
ylabel,
diff --git a/framework/pmd_output.py b/framework/pmd_output.py
index dd1e40d..2d66743 100644
--- a/framework/pmd_output.py
+++ b/framework/pmd_output.py
@@ -157,7 +157,7 @@ class PmdOutput():
config['cores'] = cores
if eal_param == '':
# use configured ports if not set
- if 'ports' not in config.keys():
+ if 'ports' not in list(config.keys()):
config['ports'] = [self.dut.ports_info[i]['pci'] for i in range(len(self.dut.ports_info))]
all_eal_param = self.dut.create_eal_parameters(fixed_prefix=fixed_prefix, socket=socket, **config)
else:
@@ -173,7 +173,7 @@ class PmdOutput():
if file_prefix:
config['prefix'] = file_prefix
- if not w_pci_list and not b_pci_list and 'ports' not in config.keys():
+ if not w_pci_list and not b_pci_list and 'ports' not in list(config.keys()):
config['ports'] = [self.dut.ports_info[i]['pci'] for i in range(len(self.dut.ports_info))]
part_eal_param = self.dut.create_eal_parameters(fixed_prefix=fixed_prefix, socket=socket, **config)
all_eal_param = part_eal_param + ' ' + other_eal_str
diff --git a/framework/qemu_kvm.py b/framework/qemu_kvm.py
index 849a4a7..aa92978 100644
--- a/framework/qemu_kvm.py
+++ b/framework/qemu_kvm.py
@@ -209,7 +209,7 @@ class QEMUKvm(VirtBase):
"""
path: absolute path for qemu emulator
"""
- if 'path' in options.keys():
+ if 'path' in list(options.keys()):
self.set_qemu_emulator(options['path'])
def has_virtual_ability(self):
@@ -281,7 +281,7 @@ class QEMUKvm(VirtBase):
"""
'enable': 'yes'
"""
- if 'enable' in options.keys() and \
+ if 'enable' in list(options.keys()) and \
options['enable'] == 'yes':
enable_kvm_boot_line = '-enable-kvm'
self.__add_boot_line(enable_kvm_boot_line)
@@ -302,10 +302,10 @@ class QEMUKvm(VirtBase):
"""
machine_boot_line='-machine'
separator = ','
- if 'machine' in options.keys() and \
+ if 'machine' in list(options.keys()) and \
options['machine']:
machine_boot_line += ' %s' % options['machine']
- if 'opt_gic_version' in options.keys() and \
+ if 'opt_gic_version' in list(options.keys()) and \
options['opt_gic_version']:
machine_boot_line += separator + 'gic_version=%s' % options['opt_gic_version']
@@ -328,7 +328,7 @@ class QEMUKvm(VirtBase):
"""
'name' : '/tmp/.qemu_vm0.pid'
"""
- if 'name' in options.keys():
+ if 'name' in list(options.keys()):
self.__add_boot_line('-pidfile %s' % options['name'])
def set_vm_name(self, vm_name):
@@ -345,7 +345,7 @@ class QEMUKvm(VirtBase):
"""
name: vm1
"""
- if 'name' in options.keys() and \
+ if 'name' in list(options.keys()) and \
options['name']:
name_boot_line = '-name %s' % options['name']
self.__add_boot_line(name_boot_line)
@@ -359,15 +359,15 @@ class QEMUKvm(VirtBase):
number: '4' #number of vcpus
cpupin: '3 4 5 6' # host cpu list
"""
- if 'model' in options.keys() and \
+ if 'model' in list(options.keys()) and \
options['model']:
cpu_boot_line = '-cpu %s' % options['model']
self.__add_boot_line(cpu_boot_line)
- if 'number' in options.keys() and \
+ if 'number' in list(options.keys()) and \
options['number']:
smp_cmd_line = '-smp %d' % int(options['number'])
self.__add_boot_line(smp_cmd_line)
- if 'cpupin' in options.keys() and \
+ if 'cpupin' in list(options.keys()) and \
options['cpupin']:
self.vcpus_pinned_to_vm = str(options['cpupin'])
@@ -375,10 +375,10 @@ class QEMUKvm(VirtBase):
"""
size: 1024
"""
- if 'size' in options.keys():
+ if 'size' in list(options.keys()):
mem_boot_line = '-m %s' % options['size']
self.__add_boot_line(mem_boot_line)
- if 'hugepage' in options.keys():
+ if 'hugepage' in list(options.keys()):
if options['hugepage'] == 'yes':
mem_boot_huge = '-object memory-backend-file,' \
+ 'id=mem,size=%sM,mem-path=%s,share=on' \
@@ -397,22 +397,22 @@ class QEMUKvm(VirtBase):
opt_media: disk
"""
separator = ','
- if 'file' in options.keys() and \
+ if 'file' in list(options.keys()) and \
options['file']:
disk_boot_line = '-drive file=%s' % options['file']
else:
return False
- if 'opt_format' in options.keys() and \
+ if 'opt_format' in list(options.keys()) and \
options['opt_format']:
disk_boot_line += separator + 'format=%s' % options['opt_format']
- if 'opt_if' in options.keys() and \
+ if 'opt_if' in list(options.keys()) and \
options['opt_if']:
disk_boot_line += separator + 'if=%s' % options['opt_if']
- if 'opt_index' in options.keys() and \
+ if 'opt_index' in list(options.keys()) and \
options['opt_index']:
disk_boot_line += separator + 'index=%s' % options['opt_index']
- if 'opt_media' in options.keys() and \
+ if 'opt_media' in list(options.keys()) and \
options['opt_media']:
disk_boot_line += separator + 'media=%s' % options['opt_media']
@@ -422,7 +422,7 @@ class QEMUKvm(VirtBase):
"""
file: /home/image/flash0.img
"""
- if 'file' in options.keys():
+ if 'file' in list(options.keys()):
pflash_boot_line = '-pflash %s' % options['file']
self.__add_boot_line(pflash_boot_line)
@@ -430,13 +430,13 @@ class QEMUKvm(VirtBase):
"""
Update VM start and login related settings
"""
- if 'wait_seconds' in options.keys():
+ if 'wait_seconds' in list(options.keys()):
self.START_TIMEOUT = int(options['wait_seconds'])
- if 'login_timeout' in options.keys():
+ if 'login_timeout' in list(options.keys()):
self.LOGIN_TIMEOUT = int(options['login_timeout'])
- if 'login_prompt' in options.keys():
+ if 'login_prompt' in list(options.keys()):
self.LOGIN_PROMPT = options['login_prompt']
- if 'password_prompt' in options.keys():
+ if 'password_prompt' in list(options.keys()):
self.PASSWORD_PROMPT = options['password_prompt']
def add_vm_login(self, **options):
@@ -444,11 +444,11 @@ class QEMUKvm(VirtBase):
user: login username of virtual machine
password: login password of virtual machine
"""
- if 'user' in options.keys():
+ if 'user' in list(options.keys()):
user = options['user']
self.username = user
- if 'password' in options.keys():
+ if 'password' in list(options.keys()):
password = options['password']
self.password = password
@@ -469,7 +469,7 @@ class QEMUKvm(VirtBase):
opt_[vlan | fd | br | mac | ...]
note:the sub-option will be decided according to the net type.
"""
- if 'type' in options.keys():
+ if 'type' in list(options.keys()):
if options['type'] == 'nic':
self.__add_vm_net_nic(**options)
if options['type'] == 'user':
@@ -490,18 +490,18 @@ class QEMUKvm(VirtBase):
baudrate: console access baudrate in kernel boot args
root: root partition details in kernel boot args
"""
- print options
- if 'kernel_img' in options.keys() and options['kernel_img']:
+ print(options)
+ if 'kernel_img' in list(options.keys()) and options['kernel_img']:
kernel_boot_line = '-kernel %s' % options['kernel_img']
else:
return False
self.__add_boot_line(kernel_boot_line)
kernel_args = ""
- if 'console' in options.keys() and options['console']:
+ if 'console' in list(options.keys()) and options['console']:
kernel_args = "console=%s" %options['console']
- if 'baudrate' in options.keys() and options['baudrate']:
+ if 'baudrate' in list(options.keys()) and options['baudrate']:
kernel_args += "," + options['baudrate']
- if 'root' in options.keys() and options['root']:
+ if 'root' in list(options.keys()) and options['root']:
kernel_args += " root=%s" %options['root']
if kernel_args:
append_boot_line = '--append \"%s\"' %kernel_args
@@ -516,7 +516,7 @@ class QEMUKvm(VirtBase):
net_boot_line = '-device '
separator = ','
- if 'opt_model' in options.keys() and \
+ if 'opt_model' in list(options.keys()) and \
options['opt_model']:
model = options['opt_model']
else:
@@ -547,7 +547,7 @@ class QEMUKvm(VirtBase):
self.nic_num = self.nic_num + 1
netdev = "id=nttsip%d" % netdev_id
net_boot_line += separator + netdev
- if 'opt_hostfwd' in options.keys() and \
+ if 'opt_hostfwd' in list(options.keys()) and \
options['opt_hostfwd']:
self.__check_net_user_opt_hostfwd(options['opt_hostfwd'])
opt_hostfwd = options['opt_hostfwd']
@@ -646,7 +646,7 @@ class QEMUKvm(VirtBase):
net_boot_line += separator + netdev
# add bridge info
- if 'opt_br' in options.keys() and \
+ if 'opt_br' in list(options.keys()) and \
options['opt_br']:
bridge = options['opt_br']
else:
@@ -654,7 +654,7 @@ class QEMUKvm(VirtBase):
self.__generate_net_config_script(str(bridge))
# add network configure script path
- if 'opt_script' in options.keys() and \
+ if 'opt_script' in list(options.keys()) and \
options['opt_script']:
script_path = options['opt_script']
else:
@@ -662,7 +662,7 @@ class QEMUKvm(VirtBase):
net_boot_line += separator + 'script=%s' % script_path
# add network configure downscript path
- if 'opt_downscript' in options.keys() and \
+ if 'opt_downscript' in list(options.keys()) and \
options['opt_downscript']:
net_boot_line += separator + \
'downscript=%s' % options['opt_downscript']
@@ -704,7 +704,7 @@ class QEMUKvm(VirtBase):
opt_[host | addr | ...]: value
note:the sub-option will be decided according to the driver.
"""
- if 'driver' in options.keys() and \
+ if 'driver' in list(options.keys()) and \
options['driver']:
if options['driver'] == 'pci-assign':
self.__add_vm_pci_assign(**options)
@@ -725,13 +725,13 @@ class QEMUKvm(VirtBase):
"""
dev_boot_line = '-device vfio-pci'
separator = ','
- if 'opt_host' in options.keys() and \
+ if 'opt_host' in list(options.keys()) and \
options['opt_host']:
dev_boot_line += separator + 'host=%s' % options['opt_host']
dev_boot_line += separator + 'id=pt_%d' % self.pt_idx
self.pt_idx += 1
self.pt_devices.append(options['opt_host'])
- if 'opt_addr' in options.keys() and \
+ if 'opt_addr' in list(options.keys()) and \
options['opt_addr']:
dev_boot_line += separator + 'addr=%s' % options['opt_addr']
self.assigned_pcis.append(options['opt_addr'])
@@ -747,13 +747,13 @@ class QEMUKvm(VirtBase):
"""
dev_boot_line = '-device pci-assign'
separator = ','
- if 'opt_host' in options.keys() and \
+ if 'opt_host' in list(options.keys()) and \
options['opt_host']:
dev_boot_line += separator + 'host=%s' % options['opt_host']
dev_boot_line += separator + 'id=pt_%d' % self.pt_idx
self.pt_idx += 1
self.pt_devices.append(options['opt_host'])
- if 'opt_addr' in options.keys() and \
+ if 'opt_addr' in list(options.keys()) and \
options['opt_addr']:
dev_boot_line += separator + 'addr=%s' % options['opt_addr']
self.assigned_pcis.append(options['opt_addr'])
@@ -770,8 +770,8 @@ class QEMUKvm(VirtBase):
separator = ','
# chardev parameter
netdev_id = 'netdev%d' % self.netdev_idx
- if 'opt_script' in options.keys() and options['opt_script']:
- if 'opt_br' in options.keys() and \
+ if 'opt_script' in list(options.keys()) and options['opt_script']:
+ if 'opt_br' in list(options.keys()) and \
options['opt_br']:
bridge = options['opt_br']
else:
@@ -779,10 +779,10 @@ class QEMUKvm(VirtBase):
self.__generate_net_config_script(str(bridge))
dev_boot_line = '-netdev tap,id=%s,script=%s' % (netdev_id, options['opt_script'])
self.netdev_idx += 1
- elif 'opt_path' in options.keys() and options['opt_path']:
+ elif 'opt_path' in list(options.keys()) and options['opt_path']:
dev_boot_line = '-chardev socket'
char_id = 'char%d' % self.char_idx
- if 'opt_server' in options.keys() and options['opt_server']:
+ if 'opt_server' in list(options.keys()) and options['opt_server']:
dev_boot_line += separator + 'id=%s' % char_id + separator + \
'path=%s' % options[
'opt_path'] + separator + '%s' % options['opt_server']
@@ -796,7 +796,7 @@ class QEMUKvm(VirtBase):
# netdev parameter
netdev_id = 'netdev%d' % self.netdev_idx
self.netdev_idx += 1
- if 'opt_queue' in options.keys() and options['opt_queue']:
+ if 'opt_queue' in list(options.keys()) and options['opt_queue']:
queue_num = options['opt_queue']
dev_boot_line = '-netdev type=vhost-user,id=%s,chardev=%s,vhostforce,queues=%s' % (
netdev_id, char_id, queue_num)
@@ -806,12 +806,12 @@ class QEMUKvm(VirtBase):
self.__add_boot_line(dev_boot_line)
# device parameter
opts = {'opt_netdev': '%s' % netdev_id}
- if 'opt_mac' in options.keys() and \
+ if 'opt_mac' in list(options.keys()) and \
options['opt_mac']:
opts['opt_mac'] = options['opt_mac']
- if 'opt_settings' in options.keys() and options['opt_settings']:
+ if 'opt_settings' in list(options.keys()) and options['opt_settings']:
opts['opt_settings'] = options['opt_settings']
- if 'opt_legacy' in options.keys() and options['opt_legacy']:
+ if 'opt_legacy' in list(options.keys()) and options['opt_legacy']:
opts['opt_legacy'] = options['opt_legacy']
self.__add_vm_virtio_net_pci(**opts)
@@ -822,7 +822,7 @@ class QEMUKvm(VirtBase):
"""
separator = ','
dev_boot_line = '-netdev tap'
- if 'opt_tap' in options.keys():
+ if 'opt_tap' in list(options.keys()):
cuse_id = options['opt_tap']
else:
cuse_id = 'vhost%d' % self.cuse_id
@@ -834,9 +834,9 @@ class QEMUKvm(VirtBase):
# device parameter
opts = {'opt_netdev': '%s' % cuse_id,
'opt_id': '%s_net' % cuse_id}
- if 'opt_mac' in options.keys() and options['opt_mac']:
+ if 'opt_mac' in list(options.keys()) and options['opt_mac']:
opts['opt_mac'] = options['opt_mac']
- if 'opt_settings' in options.keys() and options['opt_settings']:
+ if 'opt_settings' in list(options.keys()) and options['opt_settings']:
opts['opt_settings'] = options['opt_settings']
self.__add_vm_virtio_net_pci(**opts)
@@ -853,25 +853,25 @@ class QEMUKvm(VirtBase):
"""
dev_boot_line = '-device virtio-net-pci'
separator = ','
- if 'opt_netdev' in options.keys() and \
+ if 'opt_netdev' in list(options.keys()) and \
options['opt_netdev']:
dev_boot_line += separator + 'netdev=%s' % options['opt_netdev']
- if 'opt_id' in options.keys() and \
+ if 'opt_id' in list(options.keys()) and \
options['opt_id']:
dev_boot_line += separator + 'id=%s' % options['opt_id']
- if 'opt_mac' in options.keys() and \
+ if 'opt_mac' in list(options.keys()) and \
options['opt_mac']:
dev_boot_line += separator + 'mac=%s' % options['opt_mac']
- if 'opt_bus' in options.keys() and \
+ if 'opt_bus' in list(options.keys()) and \
options['opt_bus']:
dev_boot_line += separator + 'bus=%s' % options['opt_bus']
- if 'opt_addr' in options.keys() and \
+ if 'opt_addr' in list(options.keys()) and \
options['opt_addr']:
dev_boot_line += separator + 'addr=%s' % options['opt_addr']
- if 'opt_legacy' in options.keys() and \
+ if 'opt_legacy' in list(options.keys()) and \
options['opt_legacy']:
dev_boot_line += separator + 'disable-modern=%s' % options['opt_legacy']
- if 'opt_settings' in options.keys() and \
+ if 'opt_settings' in list(options.keys()) and \
options['opt_settings']:
dev_boot_line += separator + '%s' % options['opt_settings']
@@ -909,7 +909,7 @@ class QEMUKvm(VirtBase):
"""
path: if adding monitor to vm, need to specify unix socket path
"""
- if 'path' in options.keys():
+ if 'path' in list(options.keys()):
monitor_boot_line = '-monitor unix:%s,server,nowait' % options[
'path']
self.__add_boot_line(monitor_boot_line)
@@ -924,9 +924,9 @@ class QEMUKvm(VirtBase):
"""
migrate_cmd = "-incoming tcp::%(migrate_port)s"
- if 'enable' in options.keys():
+ if 'enable' in list(options.keys()):
if options['enable'] == 'yes':
- if 'port' in options.keys():
+ if 'port' in list(options.keys()):
self.migrate_port = options['port']
else:
self.migrate_port = str(
@@ -940,7 +940,7 @@ class QEMUKvm(VirtBase):
"""
Set control session options
"""
- if 'type' in options.keys():
+ if 'type' in list(options.keys()):
self.control_type = options['type']
else:
self.control_type = 'telnet'
@@ -1023,7 +1023,7 @@ class QEMUKvm(VirtBase):
return self.control_session
except Exception as e:
# when exception happened, force close serial connection and reconnect
- print RED("[%s:%s] exception [%s] happened" % (self.host_dut.crb['My IP'], self.vm_name, str(e)))
+ print(RED("[%s:%s] exception [%s] happened" % (self.host_dut.crb['My IP'], self.vm_name, str(e))))
self.close_control_session(dut_id=self.host_dut.dut_id)
return False
@@ -1066,7 +1066,7 @@ class QEMUKvm(VirtBase):
# login into Redhat os, not sure can work on all distributions
if ("x86_64 on an x86_64" not in out) and (self.LOGIN_PROMPT not in out):
- print RED("[%s:%s] not ready for login" % (self.host_dut.crb['My IP'], self.vm_name))
+ print(RED("[%s:%s] not ready for login" % (self.host_dut.crb['My IP'], self.vm_name)))
return False
else:
self.control_session.send_expect("%s" % self.username, "Password:", timeout=self.LOGIN_TIMEOUT)
@@ -1074,7 +1074,7 @@ class QEMUKvm(VirtBase):
return True
except Exception as e:
# when exception happened, force close serial connection and reconnect
- print RED("[%s:%s] exception [%s] happened" % (self.host_dut.crb['My IP'], self.vm_name, str(e)))
+ print(RED("[%s:%s] exception [%s] happened" % (self.host_dut.crb['My IP'], self.vm_name, str(e))))
self.close_control_session(dut_id=self.host_dut.dut_id)
return False
@@ -1093,7 +1093,7 @@ class QEMUKvm(VirtBase):
return True
except Exception as e:
# when exception happened, force close qga process and reconnect
- print RED("[%s:%s] QGA not ready" % (self.host_dut.crb['My IP'], self.vm_name))
+ print(RED("[%s:%s] QGA not ready" % (self.host_dut.crb['My IP'], self.vm_name)))
self.close_control_session(dut_id=self.host_dut.dut_id)
return False
@@ -1101,10 +1101,10 @@ class QEMUKvm(VirtBase):
"""
Add VM display option
"""
- if 'disable' in options.keys() and options['disable'] == 'True':
+ if 'disable' in list(options.keys()) and options['disable'] == 'True':
vnc_boot_line = '-display none'
else:
- if 'displayNum' in options.keys() and \
+ if 'displayNum' in list(options.keys()) and \
options['displayNum']:
display_num = options['displayNum']
else:
@@ -1118,10 +1118,10 @@ class QEMUKvm(VirtBase):
"""
Set VM display options
"""
- if 'disable' in options.keys():
+ if 'disable' in list(options.keys()):
vnc_option = [{'disable': 'True'}]
else:
- if 'displayNum' in options.keys():
+ if 'displayNum' in list(options.keys()):
vnc_option = [{'displayNum': options['displayNum']}]
else:
# will allocate vnc display later
@@ -1150,7 +1150,7 @@ class QEMUKvm(VirtBase):
By default VM will start with the daemonize status.
Not support starting it on the stdin now.
"""
- if 'daemon' in options.keys() and \
+ if 'daemon' in list(options.keys()) and \
options['enable'] == 'no':
pass
else:
@@ -1162,7 +1162,7 @@ class QEMUKvm(VirtBase):
usercmd: user self defined command line.
This command will be add into qemu boot command.
"""
- if 'cmd' in options.keys():
+ if 'cmd' in list(options.keys()):
cmd = options['cmd']
self.__add_boot_line(cmd)
@@ -1172,8 +1172,8 @@ class QEMUKvm(VirtBase):
"""
separator = ' '
- if 'enable' in options.keys() and options['enable'] == 'yes':
- if 'opt_num' in options.keys():
+ if 'enable' in list(options.keys()) and options['enable'] == 'yes':
+ if 'opt_num' in list(options.keys()):
opt_num = int(options['opt_num'])
else:
opt_num = 1
@@ -1524,7 +1524,7 @@ class QEMUKvm(VirtBase):
Check if the specified PCI dev is a VF.
"""
for port_info in self.host_dut.ports_info:
- if 'sriov_vfs_pci' in port_info.keys():
+ if 'sriov_vfs_pci' in list(port_info.keys()):
if dev_pci in port_info['sriov_vfs_pci']:
return True
return False
@@ -1534,7 +1534,7 @@ class QEMUKvm(VirtBase):
Map the specified VF to PF.
"""
for port_info in self.host_dut.ports_info:
- if 'sriov_vfs_pci' in port_info.keys():
+ if 'sriov_vfs_pci' in list(port_info.keys()):
if dev_pci in port_info['sriov_vfs_pci']:
return port_info['pci']
return None
@@ -1544,7 +1544,7 @@ class QEMUKvm(VirtBase):
Get the NetDevice instance of specified VF.
"""
for port_info in self.host_dut.ports_info:
- if 'vfs_port' in port_info.keys():
+ if 'vfs_port' in list(port_info.keys()):
for port in port_info['vfs_port']:
if dev_pci == port.pci:
return port
@@ -1554,7 +1554,7 @@ class QEMUKvm(VirtBase):
"""
Check if the specified VF has been used.
"""
- for pci in assigned_pcis_info.keys():
+ for pci in list(assigned_pcis_info.keys()):
if assigned_pcis_info[pci]['is_vf'] and \
assigned_pcis_info[pci]['pf_pci'] == pf_pci:
return pci
@@ -1751,8 +1751,8 @@ class QEMUKvm(VirtBase):
self.quit_control_session()
return out
except Exception as e:
- print RED("Exception happened on [%s] serial with cmd [%s]" % (self.vm_name, command))
- print RED(e)
+ print(RED("Exception happened on [%s] serial with cmd [%s]" % (self.vm_name, command)))
+ print(RED(e))
self.close_control_session(dut_id=self.host_dut.dut_id)
return 'Failed'
@@ -1892,7 +1892,7 @@ class QEMUKvm(VirtBase):
thread_reg = r'CPU #(\d+): .* thread_id=(\d+)'
output = self.__monitor_session('info', 'cpus')
thread_cores = re.findall(thread_reg, output)
- cores_map = zip(thread_cores, lcores)
+ cores_map = list(zip(thread_cores, lcores))
for thread_info, core_id in cores_map:
cpu_id, thread_id = thread_info
self.host_session.send_expect("taskset -pc %d %s" % (core_id, thread_id), "#")
diff --git a/framework/qemu_libvirt.py b/framework/qemu_libvirt.py
index 5b25dec..5e34590 100644
--- a/framework/qemu_libvirt.py
+++ b/framework/qemu_libvirt.py
@@ -165,10 +165,10 @@ class LibvirtKvm(VirtBase):
size : memory size, measured in MB
hugepage : guest memory allocated using hugepages
"""
- if 'size' in options.keys():
+ if 'size' in list(options.keys()):
memory = ET.SubElement(self.domain, 'memory', {'unit': 'MB'})
memory.text = options['size']
- if 'hugepage' in options.keys():
+ if 'hugepage' in list(options.keys()):
memoryBacking = ET.SubElement(self.domain, 'memoryBacking')
ET.SubElement(memoryBacking, 'hugepages')
@@ -188,10 +188,10 @@ class LibvirtKvm(VirtBase):
'cpupin' : '3 4 5 6' # host cpu list
"""
vcpu = 0
- if 'number' in options.keys():
+ if 'number' in list(options.keys()):
vmcpu = ET.SubElement(self.domain, 'vcpu', {'placement': 'static'})
vmcpu.text = options['number']
- if 'cpupin' in options.keys():
+ if 'cpupin' in list(options.keys()):
cputune = ET.SubElement(self.domain, 'cputune')
# cpu resource will be allocated
req_cpus = options['cpupin'].split()
@@ -230,11 +230,11 @@ class LibvirtKvm(VirtBase):
def add_vm_os(self, **options):
os = self.domain.find('os')
- if 'loader' in options.keys():
+ if 'loader' in list(options.keys()):
loader = ET.SubElement(
os, 'loader', {'readonly': 'yes', 'type': 'pflash'})
loader.text = options['loader']
- if 'nvram' in options.keys():
+ if 'nvram' in list(options.keys()):
nvram = ET.SubElement(os, 'nvram')
nvram.text = options['nvram']
@@ -310,7 +310,7 @@ class LibvirtKvm(VirtBase):
Options:
path: absolute path for qemu emulator
"""
- if 'path' in options.keys():
+ if 'path' in list(options.keys()):
self.set_qemu_emulator(options['path'])
# update emulator config
devices = self.domain.find('devices')
@@ -394,10 +394,10 @@ class LibvirtKvm(VirtBase):
ET.SubElement(graphics, 'listen', listen)
def add_vm_serial_port(self, **options):
- if 'enable' in options.keys():
+ if 'enable' in list(options.keys()):
if options['enable'].lower() == 'yes':
devices = self.domain.find('devices')
- if 'opt_type' in options.keys():
+ if 'opt_type' in list(options.keys()):
serial_type = options['opt_type']
else:
serial_type = 'unix'
@@ -429,11 +429,11 @@ class LibvirtKvm(VirtBase):
user: login username of virtual machine
password: login password of virtual machine
"""
- if 'user' in options.keys():
+ if 'user' in list(options.keys()):
user = options['user']
self.username = user
- if 'password' in options.keys():
+ if 'password' in list(options.keys()):
password = options['password']
self.password = password
@@ -553,7 +553,7 @@ class LibvirtKvm(VirtBase):
drv_opt = {}
guest_opt = {}
host_opt = {}
- for key, value in _sub_opt.iteritems():
+ for key, value in _sub_opt.items():
if key.startswith('host_'):
host_opt[key[5:]] = value
continue
@@ -638,7 +638,7 @@ class LibvirtKvm(VirtBase):
self.__add_vm_pci_assign,
}
driver = options.get('driver')
- if not driver or driver not in driver_table.keys():
+ if not driver or driver not in list(driver_table.keys()):
driver = 'pci-assign'
msg = 'use {0} configuration as default driver'.format(driver)
self.logger.warning(msg)
@@ -650,7 +650,7 @@ class LibvirtKvm(VirtBase):
Options:
default: create e1000 netdev and redirect ssh port
"""
- if 'type' in options.keys():
+ if 'type' in list(options.keys()):
if options['type'] == 'nic':
self.__add_vm_net_nic(**options)
elif options['type'] == 'tap':
@@ -664,12 +664,12 @@ class LibvirtKvm(VirtBase):
opt_addr: ''
note: PCI cards only.
"""
- if 'opt_model' in options.keys():
+ if 'opt_model' in list(options.keys()):
model = options['opt_model']
else:
model = 'e1000'
- if 'opt_hostfwd' in options.keys():
+ if 'opt_hostfwd' in list(options.keys()):
port = self.virt_pool.alloc_port(self.vm_name)
if port is None:
return
@@ -678,7 +678,7 @@ class LibvirtKvm(VirtBase):
qemu = ET.SubElement(self.domain, 'qemu:commandline')
ET.SubElement(qemu, 'qemu:arg', {'value': '-net'})
- if 'opt_addr' in options.keys():
+ if 'opt_addr' in list(options.keys()):
pci = self.__parse_pci(options['opt_addr'])
if pci is None:
return False
@@ -691,7 +691,7 @@ class LibvirtKvm(VirtBase):
% self.pciindex})
self.pciindex += 1
- if 'opt_hostfwd' in options.keys():
+ if 'opt_hostfwd' in list(options.keys()):
ET.SubElement(qemu, 'qemu:arg', {'value': '-net'})
ET.SubElement(qemu, 'qemu:arg', {'value': 'user,hostfwd='
'tcp:%s:%d-:22' % (dut_ip, port)})
@@ -729,7 +729,7 @@ class LibvirtKvm(VirtBase):
devices = self.domain.find('devices')
channel = ET.SubElement(devices, 'channel', {'type': 'unix'})
for opt in ['path', 'name']:
- if opt not in options.keys():
+ if opt not in list(options.keys()):
msg = "invalid virtio serial channel setting"
self.logger.error(msg)
return
diff --git a/framework/rst.py b/framework/rst.py
index 2f36ab1..2b8e613 100644
--- a/framework/rst.py
+++ b/framework/rst.py
@@ -108,9 +108,9 @@ class RstReport(object):
f.write('-' * len(line) + '\n')
def write_subtitle(self):
- if self._subtitle is not None:
- with open(self.rstName, "a") as f:
- f.write("%s\n" % self._subtitle)
+ if self._subtitle is not None:
+ with open(self.rstName, "a") as f:
+ f.write("%s\n" % self._subtitle)
def write_annex_title(self, text):
"""
diff --git a/framework/serializer.py b/framework/serializer.py
index 2f0545d..26f68d9 100644
--- a/framework/serializer.py
+++ b/framework/serializer.py
@@ -56,8 +56,6 @@ class Serializer(object):
is called it will return a reference to the same instance.
"""
- __metaclass__ = Singleton
-
def __init__(self):
self.volatile_cache = {}
self.filename = 'serializer.cache'
diff --git a/framework/settings.py b/framework/settings.py
index 7e8944e..ce9fc30 100644
--- a/framework/settings.py
+++ b/framework/settings.py
@@ -268,7 +268,7 @@ def get_nic_name(type):
"""
strip nic code name by nic type
"""
- for name, nic_type in NICS.items():
+ for name, nic_type in list(NICS.items()):
if nic_type == type:
return name
return 'Unknown'
@@ -278,7 +278,7 @@ def get_nic_driver(pci_id):
"""
Return linux driver for specified pci device
"""
- driverlist = dict(zip(NICS.values(), DRIVERS.keys()))
+ driverlist = dict(list(zip(list(NICS.values()), list(DRIVERS.keys()))))
try:
driver = DRIVERS[driverlist[pci_id]]
except Exception as e:
@@ -290,7 +290,7 @@ def get_netdev(crb, pci):
for port in crb.ports_info:
if pci == port['pci']:
return port['port']
- if 'vfs_port' in port.keys():
+ if 'vfs_port' in list(port.keys()):
for vf in port['vfs_port']:
if pci == vf.pci:
return vf
@@ -308,7 +308,7 @@ def get_host_ip(address):
result = socket.gethostbyaddr(address)
return result[2][0]
except:
- print "couldn't look up %s" % address
+ print("couldn't look up %s" % address)
return ''
@@ -333,7 +333,7 @@ def load_global_setting(key):
else:
env_key = "DTS_" + key
- if env_key in os.environ.keys():
+ if env_key in list(os.environ.keys()):
return os.environ[env_key]
else:
return ''
@@ -343,7 +343,7 @@ def report_error(error):
"""
Report error when error occurred
"""
- if error in DTS_ERR_TBL.keys():
+ if error in list(DTS_ERR_TBL.keys()):
os.environ[DTS_ERROR_ENV] = error
else:
os.environ[DTS_ERROR_ENV] = "GENERIC_ERR"
@@ -353,7 +353,7 @@ def exit_error():
"""
Set system exit value when error occurred
"""
- if DTS_ERROR_ENV in os.environ.keys():
+ if DTS_ERROR_ENV in list(os.environ.keys()):
ret_val = DTS_ERR_TBL[os.environ[DTS_ERROR_ENV]]
sys.exit(ret_val)
else:
@@ -366,7 +366,7 @@ def accepted_nic(pci_id):
it is selected in the execution file, otherwise it returns False.
"""
nic = load_global_setting(HOST_NIC_SETTING)
- if pci_id not in NICS.values():
+ if pci_id not in list(NICS.values()):
return False
if nic is 'any':
diff --git a/framework/ssh_pexpect.py b/framework/ssh_pexpect.py
index 979327c..8889016 100644
--- a/framework/ssh_pexpect.py
+++ b/framework/ssh_pexpect.py
@@ -12,7 +12,7 @@ Also supports transfer files to tester or DUT.
"""
-class SSHPexpect(object):
+class SSHPexpect:
def __init__(self, host, username, password, dut_id):
self.magic_prompt = "MAGIC PROMPT"
@@ -35,7 +35,7 @@ class SSHPexpect(object):
be modified along with MaxStartups value.
"""
try:
- self.session = pxssh.pxssh()
+ self.session = pxssh.pxssh(encoding='utf-8')
if ':' in self.host:
self.ip = self.host.split(':')[0]
self.port = int(self.host.split(':')[1])
@@ -48,11 +48,11 @@ class SSHPexpect(object):
self.send_expect('stty -echo', '#')
self.send_expect('stty columns 1000', "#")
except Exception as e:
- print RED(e)
+ print(RED(e))
if getattr(self, 'port', None):
suggestion = "\nSuggession: Check if the firewall on [ %s ] " % \
self.ip + "is stopped\n"
- print GREEN(suggestion)
+ print(GREEN(suggestion))
raise SSHConnectionException(self.host)
@@ -86,7 +86,7 @@ class SSHPexpect(object):
else:
return ret
except Exception as e:
- print RED("Exception happened in [%s] and output is [%s]" % (command, self.get_output_before()))
+ print(RED("Exception happened in [%s] and output is [%s]" % (command, self.get_output_before())))
raise(e)
def send_command(self, command, timeout=1):
diff --git a/framework/test_case.py b/framework/test_case.py
index b7952fa..0b91fed 100644
--- a/framework/test_case.py
+++ b/framework/test_case.py
@@ -162,14 +162,14 @@ class TestCase(object):
def verify(self, passed, description):
if not passed:
if self._enable_debug:
- print RED("Error happened, dump command history...")
+ print(RED("Error happened, dump command history..."))
self.dump_history()
- print "Error \"%s\" happened" % RED(description)
- print RED("History dump finished.")
+ print("Error \"%s\" happened" % RED(description))
+ print(RED("History dump finished."))
raise VerifyFailure(description)
def _get_nic_driver(self, nic_name):
- if nic_name in DRIVERS.keys():
+ if nic_name in list(DRIVERS.keys()):
return DRIVERS[nic_name]
return "Unknown"
@@ -227,8 +227,8 @@ class TestCase(object):
"""
Pass down subtitle for Rst report
"""
- self._rst_obj._subtitle = subtitle
- self._rst_obj.write_subtitle()
+ self._rst_obj._subtitle = subtitle
+ self._rst_obj.write_subtitle()
def _get_test_cases(self, test_name_regex):
"""
@@ -344,7 +344,7 @@ class TestCase(object):
finally:
# update expected
if load_global_setting(UPDATE_EXPECTED) == "yes" and \
- self.get_suite_cfg().has_key('update_expected') and \
+ 'update_expected' in self.get_suite_cfg() and \
self.get_suite_cfg()['update_expected'] == True:
self._suite_conf.update_case_config(SUITE_SECTION_NAME)
self.tear_down()
@@ -451,9 +451,9 @@ class TestCase(object):
Dump recorded command history
"""
for cmd_history in self.setup_history:
- print '%-20s: %s' % (BLUE(cmd_history['name']), cmd_history['command'])
+ print('%-20s: %s' % (BLUE(cmd_history['name']), cmd_history['command']))
for cmd_history in self.test_history:
- print '%-20s: %s' % (BLUE(cmd_history['name']), cmd_history['command'])
+ print('%-20s: %s' % (BLUE(cmd_history['name']), cmd_history['command']))
def wirespeed(self, nic, frame_size, num_ports):
"""
diff --git a/framework/tester.py b/framework/tester.py
index 7b05832..e6c951e 100644
--- a/framework/tester.py
+++ b/framework/tester.py
@@ -185,7 +185,7 @@ class Tester(Crb):
self.logger.error(result.strip())
for port in self.ports_info:
- if not "intf" in port.keys():
+ if not "intf" in list(port.keys()):
continue
eth = port["intf"]
out = self.send_expect("ethtool --show-priv-flags %s"
@@ -355,7 +355,7 @@ class Tester(Crb):
cached_ports_info = []
for port in self.ports_info:
port_info = {}
- for key in port.keys():
+ for key in list(port.keys()):
if type(port[key]) is str:
port_info[key] = port[key]
# need save netdev objects
@@ -432,7 +432,7 @@ class Tester(Crb):
for (pci_bus, pci_id) in self.pci_devices_info:
# ignore unknown card types
- if pci_id not in NICS.values():
+ if pci_id not in list(NICS.values()):
self.logger.info("Tester: [%s %s] %s" % (pci_bus, pci_id,
"unknow_nic"))
continue
@@ -670,7 +670,7 @@ class Tester(Crb):
"""
Callable function for parallel processes
"""
- print GREEN("Transmitting and sniffing packets, please wait few minutes...")
+ print(GREEN("Transmitting and sniffing packets, please wait few minutes..."))
return pkt.send_pkt_bg(crb=self, tx_port=intf, count=send_times, loop=0, interval=interval)
def check_random_pkts(self, portList, pktnum=2000, interval=0.01, allow_miss=True, seq_check=False, params=None):
@@ -689,7 +689,7 @@ class Tester(Crb):
for txport, rxport in portList:
txIntf = self.get_interface(txport)
rxIntf = self.get_interface(rxport)
- print GREEN("Preparing transmit packets, please wait few minutes...")
+ print(GREEN("Preparing transmit packets, please wait few minutes..."))
pkt = pkt_c()
pkt.generate_random_pkts(pktnum=pktnum, random_type=random_type, ip_increase=True, random_payload=True,
options={"layers_config": params})
@@ -721,13 +721,13 @@ class Tester(Crb):
recv_pkts = p.pktgen.pkts
# only report when received number not matched
if len(tx_pkts[txport].pktgen.pkts) > len(recv_pkts):
- print ("Pkt number not matched,%d sent and %d received\n" % (
- len(tx_pkts[txport].pktgen.pkts), len(recv_pkts)))
+ print(("Pkt number not matched,%d sent and %d received\n" % (
+ len(tx_pkts[txport].pktgen.pkts), len(recv_pkts))))
if allow_miss is False:
return False
# check each received packet content
- print GREEN("Comparing sniffed packets, please wait few minutes...")
+ print(GREEN("Comparing sniffed packets, please wait few minutes..."))
for idx in range(len(recv_pkts)):
try:
l3_type = p.strip_element_layer2('type', p_index=idx)
@@ -745,16 +745,16 @@ class Tester(Crb):
if seq_check:
if t_idx <= prev_id:
- print "Packet %d sequence not correct" % t_idx
+ print("Packet %d sequence not correct" % t_idx)
return False
else:
prev_id = t_idx
if compare_f(tx_pkts[txport].pktgen.pkts[t_idx], recv_pkts[idx], "L4") is False:
- print "Pkt received index %d not match original " \
- "index %d" % (idx, t_idx)
- print "Sent: %s" % strip_f(tx_pkts[txport].pktgen.pkts[t_idx], "L4")
- print "Recv: %s" % strip_f(recv_pkts[idx], "L4")
+ print("Pkt received index %d not match original " \
+ "index %d" % (idx, t_idx))
+ print("Sent: %s" % strip_f(tx_pkts[txport].pktgen.pkts[t_idx], "L4"))
+ print("Recv: %s" % strip_f(recv_pkts[idx], "L4"))
return False
return True
@@ -809,7 +809,7 @@ class Tester(Crb):
if self.is_pktgen and self.pktgen:
self.pktgen.quit_generator()
# only restore ports if start trex in dts
- if 'start_trex' in self.pktgen.conf.keys():
+ if 'start_trex' in list(self.pktgen.conf.keys()):
self.restore_trex_interfaces()
self.pktgen = None
elif self.ixia_packet_gen:
diff --git a/framework/texttable.py b/framework/texttable.py
index 3906d97..d4aad6f 100644
--- a/framework/texttable.py
+++ b/framework/texttable.py
@@ -1,5 +1,3 @@
-#!/usr/bin/env python
-#
# texttable - module for creating simple ASCII tables
# Copyright (C) 2003-2015 Gerome Fournier <jef(at)foutaise.org>
#
@@ -124,7 +122,7 @@ def len(iterable):
if sys.version >= '3.0':
return len(str)
else:
- return len(unicode(iterable, 'utf'))
+ return len(str(iterable, 'utf'))
except:
return iterable.__len__()
@@ -147,8 +145,8 @@ TEXT_CODES = {'bold': {'start': '\x1b[1m',
'end': '\x1b[24m'}}
class TextCodesStripper:
- keys = [re.escape(v['start']) for k,v in TEXT_CODES.items()]
- keys += [re.escape(v['end']) for k,v in TEXT_CODES.items()]
+ keys = [re.escape(v['start']) for k,v in list(TEXT_CODES.items())]
+ keys += [re.escape(v['end']) for k,v in list(TEXT_CODES.items())]
pattern = re.compile("|".join(keys))
@staticmethod
@@ -353,7 +351,7 @@ class Texttable:
# usable code for python 2.1
if header:
if hasattr(rows, '__iter__') and hasattr(rows, 'next'):
- self.header(rows.next())
+ self.header(next(rows))
else:
self.header(rows[0])
rows = rows[1:]
@@ -596,7 +594,7 @@ class Texttable:
if sys.version >= '3.0':
c = str(c, 'utf', 'replace')
else:
- c = unicode(c, 'utf', 'replace')
+ c = str(c, 'utf', 'replace')
# imarom - no wrap for now
#array.extend(textwrap.wrap(c, width))
@@ -625,7 +623,7 @@ if __name__ == '__main__':
table.add_rows([["Name", "Age", "Nickname"],
["Mr\nXavier\nHuon", 32, "Xav'"],
["Mr\nBaptiste\nClement", 1, "Baby"]])
- print(table.draw() + "\n")
+ print((table.draw() + "\n"))
table = Texttable()
table.set_deco(Texttable.HEADER)
@@ -640,4 +638,4 @@ if __name__ == '__main__':
["efghijk", 67.5434, .654, 89.6, 12800000000000000000000.00023],
["lmn", 5e-78, 5e-78, 89.4, .000000000000128],
["opqrstu", .023, 5e+78, 92., 12800000000000000000000]])
- print(table.draw())
+ print((table.draw()))
diff --git a/framework/utils.py b/framework/utils.py
index 516dc91..f6594b5 100644
--- a/framework/utils.py
+++ b/framework/utils.py
@@ -93,8 +93,8 @@ def parallel_lock(num=1):
# make sure when owned global lock, should also own update lock
if lock_info[name]['current_thread'] >= num:
if lock._is_owned():
- print RED("DUT%d %s waiting for func lock %s" % (dut_id,
- threading.current_thread().name, func.__name__))
+ print(RED("DUT%d %s waiting for func lock %s" % (dut_id,
+ threading.current_thread().name, func.__name__)))
lock.acquire()
else:
uplock.release()
@@ -154,7 +154,7 @@ def regexp(s, to_match, allString=False):
return scanner.findall(s)
m = scanner.search(s)
if m is None:
- print RED("Failed to match " + to_match + " in the string " + s)
+ print(RED("Failed to match " + to_match + " in the string " + s))
return None
return m.group(1)
@@ -200,7 +200,7 @@ def get_subclasses(module, clazz):
def copy_instance_attr(from_inst, to_inst):
- for key in from_inst.__dict__.keys():
+ for key in list(from_inst.__dict__.keys()):
to_inst.__dict__[key] = from_inst.__dict__[key]
@@ -249,7 +249,7 @@ def convert_mac2long(mac_str):
mac_hex = '0x'
for mac_part in mac_str.lower().split(':'):
mac_hex += mac_part
- ret = long(mac_hex, 16)
+ ret = int(mac_hex, 16)
return ret
def convert_mac2str(mac_long):
diff --git a/framework/virt_base.py b/framework/virt_base.py
index 31623be..c959ca0 100644
--- a/framework/virt_base.py
+++ b/framework/virt_base.py
@@ -33,7 +33,7 @@ import sys
import traceback
import threading
from random import randint
-from itertools import imap
+
import utils
import exception
@@ -127,7 +127,7 @@ class VirtBase(object):
conf.load_virt_config(self.virt_type)
global_conf = conf.get_virt_config()
for param in global_conf:
- for key in param.keys():
+ for key in list(param.keys()):
if self.find_option_index(key) is None:
self.__save_local_config(key, param[key])
@@ -153,11 +153,11 @@ class VirtBase(object):
# replace global configurations with local configurations
for param in self.local_conf:
- if 'virt_type' in param.keys():
+ if 'virt_type' in list(param.keys()):
# param 'virt_type' is for virt_base only
continue
# save local configurations
- for key in param.keys():
+ for key in list(param.keys()):
self.__save_local_config(key, param[key])
def __save_local_config(self, key, value):
@@ -165,7 +165,7 @@ class VirtBase(object):
Save the local config into the global dict self.param.
"""
for param in self.params:
- if key in param.keys():
+ if key in list(param.keys()):
param[key] = value
return
@@ -176,7 +176,7 @@ class VirtBase(object):
Compose all boot param for starting the VM.
"""
for param in self.params:
- key = param.keys()[0]
+ key = list(param.keys())[0]
value = param[key]
try:
param_func = getattr(self, 'add_vm_' + key)
@@ -185,10 +185,10 @@ class VirtBase(object):
for option in value:
param_func(**option)
else:
- print utils.RED("Virt %s function not callable!!!" % key)
+ print(utils.RED("Virt %s function not callable!!!" % key))
except AttributeError:
self.host_logger.error(traceback.print_exception(*sys.exc_info()))
- print utils.RED("Virt %s function not implemented!!!" % key)
+ print(utils.RED("Virt %s function not implemented!!!" % key))
except Exception:
self.host_logger.error(traceback.print_exception(*sys.exc_info()))
raise exception.VirtConfigParamException(key)
@@ -197,9 +197,9 @@ class VirtBase(object):
"""
Set default driver which may required when setup VM
"""
- if 'driver_name' in options.keys():
+ if 'driver_name' in list(options.keys()):
self.def_driver = options['driver_name']
- if 'driver_mode' in options.keys():
+ if 'driver_mode' in list(options.keys()):
self.driver_mode = options['driver_mode']
def find_option_index(self, option):
@@ -211,7 +211,7 @@ class VirtBase(object):
"""
index = 0
for param in self.params:
- key = param.keys()[0]
+ key = list(param.keys())[0]
if key.strip() == option.strip():
return index
index += 1
@@ -224,7 +224,7 @@ class VirtBase(object):
"""
mac_head = '00:00:00:'
mac_tail = ':'.join(
- ['%02x' % x for x in imap(lambda x:randint(0, 255), range(3))])
+ ['%02x' % x for x in map(lambda x:randint(0, 255), list(range(3)))])
return mac_head + mac_tail
def get_vm_ip(self):
@@ -296,9 +296,9 @@ class VirtBase(object):
except Exception as vm_except:
if self.handle_exception(vm_except):
- print utils.RED("Handled exception " + str(type(vm_except)))
+ print(utils.RED("Handled exception " + str(type(vm_except))))
else:
- print utils.RED("Unhandled exception " + str(type(vm_except)))
+ print(utils.RED("Unhandled exception " + str(type(vm_except))))
if callable(self.callback):
self.callback()
@@ -321,9 +321,9 @@ class VirtBase(object):
except Exception as vm_except:
if self.handle_exception(vm_except):
- print utils.RED("Handled exception " + str(type(vm_except)))
+ print(utils.RED("Handled exception " + str(type(vm_except))))
else:
- print utils.RED("Unhandled exception " + str(type(vm_except)))
+ print(utils.RED("Unhandled exception " + str(type(vm_except))))
if callable(self.callback):
self.callback()
@@ -341,9 +341,9 @@ class VirtBase(object):
vm_dut = self.instantiate_vm_dut(set_target, cpu_topo, bind_dev=False, autodetect_topo=False)
except Exception as vm_except:
if self.handle_exception(vm_except):
- print utils.RED("Handled exception " + str(type(vm_except)))
+ print(utils.RED("Handled exception " + str(type(vm_except))))
else:
- print utils.RED("Unhandled exception " + str(type(vm_except)))
+ print(utils.RED("Unhandled exception " + str(type(vm_except))))
return None
@@ -398,9 +398,9 @@ class VirtBase(object):
"""
param_len = len(self.params)
for i in range(param_len):
- if 'disk' in self.params[i].keys():
+ if 'disk' in list(self.params[i].keys()):
value = self.params[i]['disk'][0]
- if 'file' in value.keys():
+ if 'file' in list(value.keys()):
host_ip = self.host_dut.get_ip_address()
return host_ip + ':' + self.host_dut.test_classname + ':' + value['file']
return None
diff --git a/framework/virt_common.py b/framework/virt_common.py
index 094d9d8..628cadf 100644
--- a/framework/virt_common.py
+++ b/framework/virt_common.py
@@ -43,7 +43,7 @@ def VM(dut, vm_name, suite_name):
# Default virt_type is 'KVM'
virt_type = 'KVM'
for param in local_conf:
- if 'virt_type' in param.keys():
+ if 'virt_type' in list(param.keys()):
virt_type = param['virt_type'][0]['virt_type']
if virt_type == 'KVM':
diff --git a/framework/virt_dut.py b/framework/virt_dut.py
index a916b72..1c6554d 100644
--- a/framework/virt_dut.py
+++ b/framework/virt_dut.py
@@ -123,13 +123,13 @@ class VirtDut(DPDKdut):
"""
port_num = len(self.ports_info)
self.ports_map = [-1] * port_num
- for key in self.ports_cfg.keys():
+ for key in list(self.ports_cfg.keys()):
index = int(key)
if index >= port_num:
- print RED("Can not found [%d ]port info" % index)
+ print(RED("Can not found [%d ]port info" % index))
continue
- if 'peer' in self.ports_cfg[key].keys():
+ if 'peer' in list(self.ports_cfg[key].keys()):
tester_pci = self.ports_cfg[key]['peer']
# find tester_pci index
pci_idx = self.tester.get_local_index(tester_pci)
@@ -233,7 +233,7 @@ class VirtDut(DPDKdut):
total_phycores = socks * cores
# cores should match cpu_topo
if total != len(cpuinfo):
- print RED("Core number not matched!!!")
+ print(RED("Core number not matched!!!"))
else:
for core in range(total):
thread = core / total_phycores
@@ -281,7 +281,7 @@ class VirtDut(DPDKdut):
itf = port.get_interface_name()
self.send_expect("ifconfig %s up" % itf, "# ")
time.sleep(30)
- print self.send_expect("ip link ls %s" % itf, "# ")
+ print(self.send_expect("ip link ls %s" % itf, "# "))
else:
self.logger.info(
"NOT FOUND DRIVER FOR PORT (%s|%s)!!!" % (pci_bus, pci_id))
@@ -401,7 +401,7 @@ class VirtDut(DPDKdut):
vfs = remoteport.get_sriov_vfs_pci()
# if hostpci is vf of tester port
if hostpci == remotepci or hostpci in vfs:
- print RED("Skip ping from same PF device")
+ print(RED("Skip ping from same PF device"))
continue
ipv6 = self.get_ipv6_address(vmPort)
diff --git a/framework/virt_resource.py b/framework/virt_resource.py
index f1cbe65..4356ee5 100644
--- a/framework/virt_resource.py
+++ b/framework/virt_resource.py
@@ -1,4 +1,3 @@
-#!/usr/bin/python
# BSD LICENSE
#
# Copyright(c) 2010-2015 Intel Corporation. All rights reserved.
@@ -163,7 +162,7 @@ class VirtResource(object):
cores = []
if vm == '':
- print "Alloc cpu request virtual machine name!!!"
+ print("Alloc cpu request virtual machine name!!!")
return cores
# if vm has been allocated cores, just return them
@@ -178,12 +177,12 @@ class VirtResource(object):
cores.append(str(core))
number = number - 1
if number != 0:
- print "Can't allocated requested cpu!!!"
+ print("Can't allocated requested cpu!!!")
if corelist is not None:
for core in corelist:
if self.__core_isused(int(core)) is True:
- print "Core %s has been used!!!" % core
+ print("Core %s has been used!!!" % core)
else:
if self.__core_on_socket(int(core), socket) is True:
self.__core_used(int(core))
@@ -236,12 +235,12 @@ class VirtResource(object):
ports.append(pci)
number = number - 1
if number != 0:
- print "Can't allocated requested PF devices!!!"
+ print("Can't allocated requested PF devices!!!")
if pflist is not None:
for pci in pflist:
if self.__port_isused(pci) is True:
- print "Port %s has been used!!!" % pci
+ print("Port %s has been used!!!" % pci)
else:
if self.__port_on_socket(pci, socket) is True:
self.__port_used(core)
@@ -269,11 +268,11 @@ class VirtResource(object):
"""
vfs = []
if vm == '':
- print "Alloc VF request vitual machine name!!!"
+ print("Alloc VF request vitual machine name!!!")
return vfs
if pf_pci == '':
- print "Alloc VF request PF pci address!!!"
+ print("Alloc VF request PF pci address!!!")
return vfs
for vf_info in self.vfs_info:
@@ -344,14 +343,14 @@ class VirtResource(object):
"""
Check whether port has been pre-allocated
"""
- for vm_info in self.allocated_info.values():
- if vm_info.has_key('hostport') and port == vm_info['hostport']:
+ for vm_info in list(self.allocated_info.values()):
+ if 'hostport' in vm_info and port == vm_info['hostport']:
return True
- if vm_info.has_key('serialport') and port == vm_info['serialport']:
+ if 'serialport' in vm_info and port == vm_info['serialport']:
return True
- if vm_info.has_key('migrateport') and port == vm_info['migrateport']:
+ if 'migrateport' in vm_info and port == vm_info['migrateport']:
return True
- if vm_info.has_key('displayport') and port == (vm_info['displayport'] + 5900):
+ if 'displayport' in vm_info and port == (vm_info['displayport'] + 5900):
return True
return False
@@ -366,7 +365,7 @@ class VirtResource(object):
global INIT_DISPLAY_PORT
if vm == '':
- print "Alloc host port request vitual machine name!!!"
+ print("Alloc host port request vitual machine name!!!")
return None
if port_type == 'connect':
@@ -492,44 +491,44 @@ if __name__ == "__main__":
'peer': 'IXIA:6.8', 'type': '8086:10fb'}]
virt_pool = VirtResource(dut)
- print "Alloc two PF devices on socket 1 from VM"
- print virt_pool.alloc_pf(vm='test1', number=2, socket=1)
+ print("Alloc two PF devices on socket 1 from VM")
+ print(virt_pool.alloc_pf(vm='test1', number=2, socket=1))
virt_pool.add_vf_on_pf(pf_pci='08:00.0', vflist=[
'08:10.0', '08:10.2', '08:10.4', '08:10.6'])
virt_pool.add_vf_on_pf(pf_pci='08:00.1', vflist=[
'08:10.1', '08:10.3', '08:10.5', '08:10.7'])
- print "Add VF devices to resource pool"
- print virt_pool.vfs_info
+ print("Add VF devices to resource pool")
+ print(virt_pool.vfs_info)
- print "Alloc VF device from resource pool"
- print virt_pool.alloc_vf_from_pf(vm='test1', pf_pci='08:00.0', number=2)
- print virt_pool.used_vfs
- print "Alloc VF device from resource pool"
- print virt_pool.alloc_vf_from_pf(vm='test2', pf_pci='08:00.1', vflist=['08:10.3', '08:10.5'])
- print virt_pool.used_vfs
+ print("Alloc VF device from resource pool")
+ print(virt_pool.alloc_vf_from_pf(vm='test1', pf_pci='08:00.0', number=2))
+ print(virt_pool.used_vfs)
+ print("Alloc VF device from resource pool")
+ print(virt_pool.alloc_vf_from_pf(vm='test2', pf_pci='08:00.1', vflist=['08:10.3', '08:10.5']))
+ print(virt_pool.used_vfs)
- print "Del VF devices from resource pool"
+ print("Del VF devices from resource pool")
virt_pool.del_vf_on_pf(pf_pci='08:00.0', vflist=['08:10.4', '08:10.2'])
- print virt_pool.vfs_info
+ print(virt_pool.vfs_info)
virt_pool.reserve_cpu('e')
- print "Reserve three cores from resource pool"
- print virt_pool.unused_cores
- print "Alloc two cores on socket1 for VM-test1"
- print virt_pool.alloc_cpu(vm="test1", number=2, socket=1)
- print "Alloc two cores in list for VM-test2"
- print virt_pool.alloc_cpu(vm="test2", corelist=['4', '5'])
- print "Alloc two cores for VM-test3"
- print virt_pool.alloc_cpu(vm="test3", number=2)
- print "Alloc port for VM-test1"
- print virt_pool.alloc_port(vm='test1')
- print "Alloc information after allocated"
- print virt_pool.allocated_info
-
- print "Get cores on VM-test1"
- print virt_pool.get_cpu_on_vm("test1")
- print "Get pfs on VM-test1"
- print virt_pool.get_pfs_on_vm("test1")
- print "Get vfs on VM-test2"
- print virt_pool.get_vfs_on_vm("test2")
+ print("Reserve three cores from resource pool")
+ print(virt_pool.unused_cores)
+ print("Alloc two cores on socket1 for VM-test1")
+ print(virt_pool.alloc_cpu(vm="test1", number=2, socket=1))
+ print("Alloc two cores in list for VM-test2")
+ print(virt_pool.alloc_cpu(vm="test2", corelist=['4', '5']))
+ print("Alloc two cores for VM-test3")
+ print(virt_pool.alloc_cpu(vm="test3", number=2))
+ print("Alloc port for VM-test1")
+ print(virt_pool.alloc_port(vm='test1'))
+ print("Alloc information after allocated")
+ print(virt_pool.allocated_info)
+
+ print("Get cores on VM-test1")
+ print(virt_pool.get_cpu_on_vm("test1"))
+ print("Get pfs on VM-test1")
+ print(virt_pool.get_pfs_on_vm("test1"))
+ print("Get vfs on VM-test2")
+ print(virt_pool.get_vfs_on_vm("test2"))
diff --git a/framework/virt_scene.py b/framework/virt_scene.py
index 73f7f19..e67b3b6 100644
--- a/framework/virt_scene.py
+++ b/framework/virt_scene.py
@@ -1,4 +1,3 @@
-#!/usr/bin/python
# BSD LICENSE
#
# Copyright(c) 2010-2015 Intel Corporation. All rights reserved.
@@ -88,12 +87,12 @@ class VirtScene(object):
def prepare_vm(self):
host_cfg = None
- for conf in self.vm_confs.keys():
+ for conf in list(self.vm_confs.keys()):
if conf == 'scene':
for cfg in self.vm_confs['scene']:
- if 'suite' in cfg.keys():
+ if 'suite' in list(cfg.keys()):
self.prepare_suite(cfg['suite'])
- if 'host' in cfg.keys():
+ if 'host' in list(cfg.keys()):
self.host_bound = True
host_cfg = cfg['host'][0]
self.vm_confs.pop('scene')
@@ -111,7 +110,7 @@ class VirtScene(object):
def cleanup_vm(self):
# reload config for has been changed when handle config
self.load_config()
- for conf in self.vm_confs.keys():
+ for conf in list(self.vm_confs.keys()):
if conf != 'scene':
vm_name = conf
vm_conf = self.vm_confs[vm_name]
@@ -119,10 +118,10 @@ class VirtScene(object):
def prepare_suite(self, conf):
for param in conf:
- if 'dut' in param.keys():
+ if 'dut' in list(param.keys()):
if param['dut'] == 'vm_dut':
self.vm_dut_enable = True
- if 'type' in param.keys():
+ if 'type' in list(param.keys()):
if param['type'] == 'xen':
self.vm_type = 'xen'
# not implement yet
@@ -131,20 +130,20 @@ class VirtScene(object):
# not implement yet
if param['type'] == 'container':
self.vm_type = 'container'
- if 'portmap' in param.keys():
+ if 'portmap' in list(param.keys()):
if param['portmap'] == 'cfg':
self.auto_portmap = False
def prepare_host(self, **opts):
- if 'dpdk' not in opts.keys():
- print utils.RED("Scenario host parameter request dpdk option!!!")
+ if 'dpdk' not in list(opts.keys()):
+ print(utils.RED("Scenario host parameter request dpdk option!!!"))
raise VirtConfigParamException('host')
- if 'cores' not in opts.keys():
- print utils.RED("Scenario host parameter request cores option!!!")
+ if 'cores' not in list(opts.keys()):
+ print(utils.RED("Scenario host parameter request cores option!!!"))
raise VirtConfigParamException('host')
- if 'target' in opts.keys():
+ if 'target' in list(opts.keys()):
target = opts['target']
else:
target = self.def_target
@@ -161,11 +160,11 @@ class VirtScene(object):
def prepare_cpu(self, vm_name, conf):
cpu_param = {}
for params in conf:
- if 'cpu' in params.keys():
+ if 'cpu' in list(params.keys()):
cpu_conf = params['cpu'][0]
break
- if 'skipcores' in cpu_conf.keys():
+ if 'skipcores' in list(cpu_conf.keys()):
cpus = cpu_conf['skipcores'].split()
# remove invalid configured core
for cpu in cpus:
@@ -176,7 +175,7 @@ class VirtScene(object):
# reserve those skipped cores
self.host_dut.virt_pool.reserve_cpu(core_mask)
- if 'numa' in cpu_conf.keys():
+ if 'numa' in list(cpu_conf.keys()):
if cpu_conf['numa'] == 'auto':
numa = self.host_dut.ports_info[0]['port'].socket
else:
@@ -184,22 +183,22 @@ class VirtScene(object):
else:
numa = 0
- if 'number' in cpu_conf.keys():
+ if 'number' in list(cpu_conf.keys()):
num = int(cpu_conf['number'])
else:
num = 2
- if 'model' in cpu_conf.keys():
+ if 'model' in list(cpu_conf.keys()):
model = cpu_conf['model']
else:
model = 'host'
cpu_topo = ''
- if 'cpu_topo' in cpu_conf.keys():
+ if 'cpu_topo' in list(cpu_conf.keys()):
cpu_topo = cpu_conf['cpu_topo']
pin_cores = []
- if 'cpu_pin' in cpu_conf.keys():
+ if 'cpu_pin' in list(cpu_conf.keys()):
pin_cores = cpu_conf['cpu_pin'].split()
if len(pin_cores):
@@ -222,7 +221,7 @@ class VirtScene(object):
def prepare_devices(self, conf):
for params in conf:
- if 'dev_gen' in params.keys():
+ if 'dev_gen' in list(params.keys()):
index = conf.index(params)
for param in params['dev_gen']:
self.handle_dev_gen(**param)
@@ -231,19 +230,19 @@ class VirtScene(object):
def cleanup_devices(self, conf):
for params in conf:
- if 'dev_gen' in params.keys():
+ if 'dev_gen' in list(params.keys()):
for param in params['dev_gen']:
self.handle_dev_destroy(**param)
def prepare_vmdevice(self, conf):
for params in conf:
- if 'device' in params.keys():
+ if 'device' in list(params.keys()):
for param in params['device']:
- if 'vf_idx' in param.keys():
+ if 'vf_idx' in list(param.keys()):
new_param = self.prepare_vf_conf(param)
index = params['device'].index(param)
params['device'][index] = new_param
- elif 'pf_idx' in param.keys():
+ elif 'pf_idx' in list(param.keys()):
new_param = self.prepare_pf_conf(param)
index = params['device'].index(param)
params['device'][index] = new_param
@@ -270,7 +269,7 @@ class VirtScene(object):
def prepare_vf_conf(self, param):
vf_param = {}
# strip vf pci id
- if 'pf_dev' in param.keys():
+ if 'pf_dev' in list(param.keys()):
pf = int(param['pf_dev'])
pf_net = self.host_dut.ports_info[pf]['port']
vfs = self.host_dut.ports_info[pf]['vfs_port']
@@ -282,10 +281,10 @@ class VirtScene(object):
vf_param['opt_host'] = vf_pci
if param['guestpci'] != 'auto':
vf_param['opt_addr'] = param['guestpci']
- if 'mac' in param.keys():
+ if 'mac' in list(param.keys()):
pf_net.set_vf_mac_addr(vf_idx, param['mac'])
else:
- print utils.RED("Invalid vf device config, request pf_dev")
+ print(utils.RED("Invalid vf device config, request pf_dev"))
return vf_param
@@ -298,33 +297,33 @@ class VirtScene(object):
self.reg_postvm_cmds(command)
def handle_dev_gen(self, **opts):
- if 'pf_idx' in opts.keys():
+ if 'pf_idx' in list(opts.keys()):
port = int(opts['pf_idx'])
- if 'vf_num' in opts.keys():
+ if 'vf_num' in list(opts.keys()):
vf_num = int(opts['vf_num'])
else:
- print utils.RED("No vf_num for port %d, assum one VF" % port)
+ print(utils.RED("No vf_num for port %d, assum one VF" % port))
vf_num = 1
- if 'driver' in opts.keys():
+ if 'driver' in list(opts.keys()):
driver = opts['driver']
try:
- print utils.GREEN("create vf %d %d %s" % (port, vf_num, driver))
+ print(utils.GREEN("create vf %d %d %s" % (port, vf_num, driver)))
self.host_dut.generate_sriov_vfs_by_port(port, vf_num, driver)
self.reset_pf_cmds(port)
except:
- print utils.RED("Failed to create vf as requested!!!")
+ print(utils.RED("Failed to create vf as requested!!!"))
raise VirtDeviceCreateException
def handle_dev_destroy(self, **opts):
- if 'pf_idx' in opts.keys():
+ if 'pf_idx' in list(opts.keys()):
port = int(opts['pf_idx'])
try:
- print utils.GREEN("destroy vfs on port %d" % port)
+ print(utils.GREEN("destroy vfs on port %d" % port))
self.host_dut.destroy_sriov_vfs_by_port(port)
except:
- print utils.RED("Failed to destroy vf as requested!!!")
+ print(utils.RED("Failed to destroy vf as requested!!!"))
def reg_prevm_cmds(self, command):
"""
@@ -344,7 +343,7 @@ class VirtScene(object):
def run_pre_cmds(self):
for cmd in self.pre_cmds:
if cmd['type'] == 'vm':
- print utils.RED("Can't run vm command when vm not ready")
+ print(utils.RED("Can't run vm command when vm not ready"))
elif cmd['type'] == 'host':
crb = self.host_dut
elif cmd['type'] == 'tester':
@@ -352,17 +351,17 @@ class VirtScene(object):
else:
crb = self.host_dut
- if 'expect' not in cmd.keys():
+ if 'expect' not in list(cmd.keys()):
expect = "# "
else:
expect = cmd['expect']
- if 'verify' not in cmd.keys():
+ if 'verify' not in list(cmd.keys()):
verify = False
else:
verify = cmd['verify']
- if 'timeout' not in cmd.keys():
+ if 'timeout' not in list(cmd.keys()):
timeout = 5
else:
timeout = cmd['timeout']
@@ -371,7 +370,7 @@ class VirtScene(object):
verify=verify)
if type(ret) is int and ret != 0:
- print utils.RED("Failed to run command %s" % cmd['command'])
+ print(utils.RED("Failed to run command %s" % cmd['command']))
raise VirtVmOperationException
def reg_postvm_cmds(self, command):
@@ -399,17 +398,17 @@ class VirtScene(object):
else:
crb = self.host_dut
- if 'expect' not in cmd.keys():
+ if 'expect' not in list(cmd.keys()):
expect = "# "
else:
expect = cmd['expect']
- if 'verify' not in cmd.keys():
+ if 'verify' not in list(cmd.keys()):
verify = False
else:
verify = cmd['verify']
- if 'timeout' not in cmd.keys():
+ if 'timeout' not in list(cmd.keys()):
timeout = 5
else:
timeout = cmd['timeout']
@@ -418,12 +417,12 @@ class VirtScene(object):
verify=verify)
if type(ret) is int and ret != 0:
- print utils.RED("Failed to run command %s" % cmd['command'])
+ print(utils.RED("Failed to run command %s" % cmd['command']))
raise VirtVmOperationException
def merge_params(self, vm, params):
for param in params:
- index = vm.find_option_index(param.keys()[0])
+ index = vm.find_option_index(list(param.keys())[0])
if index is not None:
vm.params[index] = param
else:
@@ -434,14 +433,14 @@ class VirtScene(object):
def get_cputopo(self, params):
for param in params:
- if 'cpu' in param.keys():
+ if 'cpu' in list(param.keys()):
cpu_topo = param['cpu'][0]['cputopo']
return cpu_topo
def start_vms(self):
self.vms = []
if self.vm_type == 'kvm':
- for vm_name in self.vm_confs.keys():
+ for vm_name in list(self.vm_confs.keys()):
# tricky here, QEMUKvm based on suite and vm name
# suite is virt_global, vm_name just the type
vm = QEMUKvm(self.host_dut, self.vm_type.upper(),
@@ -468,12 +467,12 @@ class VirtScene(object):
self.vms.append(vm_info)
except Exception as e:
- print utils.RED("Failure for %s" % str(e))
+ print(utils.RED("Failure for %s" % str(e)))
def get_vm_duts(self):
duts = []
for vm_info in self.vms:
- for vm_obj in vm_info.keys():
+ for vm_obj in list(vm_info.keys()):
if 'session' in vm_obj:
duts.append(vm_info[vm_obj])
@@ -488,18 +487,18 @@ class VirtScene(object):
def set_target(self, target):
for vm_info in self.vms:
- for vm_obj in vm_info.keys():
+ for vm_obj in list(vm_info.keys()):
if 'session' in vm_obj:
vm_info[vm_obj].set_target(target)
def destroy_scene(self):
for vm_info in self.vms:
- for vm_obj in vm_info.keys():
+ for vm_obj in list(vm_info.keys()):
if 'session' in vm_obj:
vm_info[vm_obj].kill_all()
vm_info[vm_obj].close()
vm_info[vm_obj].logger.logger_exit()
- for vm_obj in vm_info.keys():
+ for vm_obj in list(vm_info.keys()):
if 'session' not in vm_obj:
vm_info[vm_obj].stop()
vm_info[vm_obj] = None
@@ -511,11 +510,11 @@ if __name__ == "__main__":
class QEMUKvm():
def __init__(self, dut, vm_name, suite_name):
- print vm_name
- print suite_name
+ print(vm_name)
+ print(suite_name)
def start(self):
- print self.params
+ print(self.params)
return True
class simple_dev(object):
@@ -540,7 +539,7 @@ if __name__ == "__main__":
def send_expect(self, cmds, expected, timeout=5,
alt_session=False, verify=False):
- print cmds + "---" + expected
+ print(cmds + "---" + expected)
class simple_resource(object):
@@ -548,10 +547,10 @@ if __name__ == "__main__":
pass
def reserve_cpu(self, coremask):
- print "reserve " + coremask
+ print("reserve " + coremask)
def alloc_cpu(self, vm='', number=-1, socket=-1, corelist=None):
- print "alloc %s num %d on socket %d" % (vm, number, socket)
+ print("alloc %s num %d on socket %d" % (vm, number, socket))
dut = simple_dut()
scene = VirtScene(dut, None, "vf_passthrough")
--
2.17.1
next prev parent reply other threads:[~2020-01-13 7:38 UTC|newest]
Thread overview: 7+ messages / expand[flat|nested] mbox.gz Atom feed top
2020-01-12 22:18 [dts] [next][PATCH V1 0/5] dts: modify dts " xinfengx
2020-01-12 22:18 ` xinfengx [this message]
2020-01-12 22:18 ` [dts] [next][PATCH V1 2/5] tests: modify test suites " xinfengx
2020-01-12 22:18 ` [dts] [next][PATCH V1 3/5] dep: modify dts dep " xinfengx
2020-01-12 22:18 ` [dts] [next][PATCH V1 4/5] nics: modify dts nics " xinfengx
2020-01-12 22:18 ` [dts] [next][PATCH V1 5/5] tools: modify dts tools " xinfengx
2020-01-16 5:47 ` [dts] [next][PATCH V1 0/5] dts: modify dts " Tu, Lijuan
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=20200112221831.12192-2-xinfengx.zhao@intel.com \
--to=xinfengx.zhao@intel.com \
--cc=dts@dpdk.org \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).