Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Convert to Python 3 #1128

Merged
merged 57 commits into from
Nov 15, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
57 commits
Select commit Hold shift + click to select a range
8eba0b8
Conform with Python 3 syntax
jleveque Sep 21, 2020
10e7c84
More Python 3 fixes
jleveque Sep 22, 2020
6e404cb
Make syntax compliant
jleveque Sep 22, 2020
e4a18b3
More manual changes
jleveque Sep 23, 2020
f795f10
[config/main.py] Replace map calls with for loop
jleveque Oct 3, 2020
fb001ba
Remove unnecessary casts from range to list
jleveque Oct 5, 2020
2513adf
[config/main.py] Add spaces after commas, prettify line breaks
jleveque Oct 5, 2020
60b9d8b
[config/main.py] Simplify line
jleveque Oct 9, 2020
c4e1e9a
Simplify check
jleveque Oct 10, 2020
95e97f6
[conftest.py] Go back to aboslute import to work with new changes
jleveque Oct 14, 2020
13c77d3
Update comments
jleveque Oct 17, 2020
d6fe8f2
Convert new consutil/lib.py changes to Python 3
jleveque Nov 4, 2020
5bfa5ac
[show/fgnhg.py] Convert to Python 3
jleveque Nov 4, 2020
f78840b
More updates
jleveque Nov 5, 2020
2d08766
Fix conftest.py
jleveque Nov 5, 2020
48d4e8e
Fix tests/system_health_test.py
jleveque Nov 5, 2020
4b0d47a
Fix conftest.py
jleveque Nov 5, 2020
19f2c50
Don't pass 'decode_responses=True' to SonicV2Connector as it is no lo…
jleveque Nov 6, 2020
1977972
Convert sonic_sku_create.py and related tests to Python 3
jleveque Nov 6, 2020
14699f2
More unicode -> str
jleveque Nov 9, 2020
5b7aafb
Make syntax Python 3-compliant
jleveque Nov 9, 2020
5d917e6
Set universal_newlines=True for all subprocess commands where stdout …
jleveque Nov 9, 2020
cd6e41f
Fix up crm_test.py
jleveque Nov 10, 2020
824bbb4
Alphabetize
jleveque Nov 11, 2020
ee359a8
Update README.md to reflect building and testing Python 3 package
jleveque Nov 12, 2020
9417e85
Fix the path of the sonic_sku_create.py script
jleveque Nov 12, 2020
2a36866
[config/feature.py] Arrange imports
jleveque Nov 13, 2020
f585baa
Remove unnecessary conversion to list
jleveque Nov 13, 2020
165ba67
Don't pass 'version' to ArgumentParser constructor; deprecated in Pyt…
jleveque Nov 13, 2020
3c0a7ee
Replace some missed dict.iteritems() with dict.items()
jleveque Nov 14, 2020
eb4d163
[aclshow] Open COUNTER_POSITION file in text mode, not binary
jleveque Nov 14, 2020
318f918
Remove support for Python 2
jleveque Nov 14, 2020
ded2b3a
Replace 'universal_newline=True' with new (as of Python 3.7) alias 't…
jleveque Nov 14, 2020
6234a4e
Replace '__builtin__' with 'builtins'
jleveque Nov 14, 2020
fbb7c40
Update expected output for CRM tests (order changed)
jleveque Nov 14, 2020
cf8d3cc
Update expected output for fgnhg tests (order changed)
jleveque Nov 14, 2020
c8606f4
Fix filter_fdb_entries.py
jleveque Nov 14, 2020
24e86db
Update shebangs to python3
jleveque Nov 14, 2020
2b26277
Pickle fixes to work with Python 3
jleveque Nov 14, 2020
1a6ff76
itervalues -> values, iterkeys -> keys
jleveque Nov 14, 2020
e38a403
[intfutil] Fix print statements
jleveque Nov 14, 2020
ee02aa2
[intfutil] Fix another missed line which wasn't Python 3-compliant
jleveque Nov 14, 2020
3f224ee
Update expected output for drops_group_test tests (order changed)
jleveque Nov 14, 2020
f210dbf
More Python 3 fixes
jleveque Nov 14, 2020
0771e0b
Add 'text=True' param to all subprocess.check_output() calls
jleveque Nov 14, 2020
1c47985
Replace 'file.next()' with 'next(file)' to comply with Python 3
jleveque Nov 14, 2020
139aa89
Update expected output for system_health_test tests (order changed)
jleveque Nov 14, 2020
a14c529
Update expected output for vlan_test tests (order changed)
jleveque Nov 14, 2020
d39bae2
Python 3 fix for watermarkstat
jleveque Nov 14, 2020
a28fec8
[show/vlan] Remove unnecessary str() conversions
jleveque Nov 14, 2020
254d57a
[show/vlan] Fix '<' not supported between instances of 'tuple' and 'str'
jleveque Nov 14, 2020
75de4f2
[pcmping] xrange() -> range()
jleveque Nov 14, 2020
7472e21
Remove unnecessary list() conversions
jleveque Nov 14, 2020
bec1ae8
[acl_loader/main.py] Update methods from ipaddr module forms to ipadd…
jleveque Nov 14, 2020
bb029e1
Remove shebangs and main() functions from files which do not need them
jleveque Nov 14, 2020
6b019ab
[pcmping] Revert unnecessary changes
jleveque Nov 14, 2020
800350f
Remove duplicate import
jleveque Nov 14, 2020
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 8 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,12 @@ Currently, this list of dependencies is as follows:

- libyang_1.0.73_amd64.deb
- libyang-cpp_1.0.73_amd64.deb
- python2-yang_1.0.73_amd64.deb
- python3-yang_1.0.73_amd64.deb
- redis_dump_load-1.1-py2-none-any.whl
- swsssdk-2.0.1-py2-none-any.whl
- sonic_py_common-1.0-py2-none-any.whl
- sonic_config_engine-1.0-py2-none-any.whl
- sonic_yang_mgmt-1.0-py2-none-any.whl
- redis_dump_load-1.1-py3-none-any.whl
- swsssdk-2.0.1-py3-none-any.whl
- sonic_py_common-1.0-py3-none-any.whl
- sonic_config_engine-1.0-py3-none-any.whl
- sonic_yang_mgmt-1.0-py3-none-any.whl
- sonic_yang_models-1.0-py3-none-any.whl


Expand All @@ -43,7 +42,7 @@ A convenient alternative is to let the SONiC build system configure a build envi

2. Build the sonic-utilities Python wheel package inside the Buster slave container, and tell the build system to keep the container alive when finished
```
make NOJESSIE=1 NOSTRETCH=1 KEEP_SLAVE_ON=yes target/python-wheels/sonic_utilities-1.2-py2-none-any.whl
make NOJESSIE=1 NOSTRETCH=1 KEEP_SLAVE_ON=yes target/python-wheels/sonic_utilities-1.2-py3-none-any.whl
```

3. When the build finishes, your prompt will change to indicate you are inside the slave container. Change into the `src/sonic-utilities/` directory
Expand All @@ -56,13 +55,13 @@ A convenient alternative is to let the SONiC build system configure a build envi
#### To build

```
python2 setup.py bdist_wheel
python3 setup.py bdist_wheel
```

#### To run unit tests

```
python2 setup.py test
python3 setup.py test
```


Expand Down
54 changes: 27 additions & 27 deletions acl_loader/main.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#!/usr/bin/env python
#!/usr/bin/env python3

import click
import ipaddr
import ipaddress
import json
import syslog

Expand Down Expand Up @@ -30,7 +30,7 @@ def error(msg):


def deep_update(dst, src):
for key, value in src.iteritems():
for key, value in src.items():
if isinstance(value, dict):
node = dst.setdefault(key, {})
deep_update(node, value)
Expand Down Expand Up @@ -182,7 +182,7 @@ def read_policers_info(self):
# For multi-npu platforms we will read from any one of front asic namespace
# config db as the information should be same across all config db
if self.per_npu_configdb:
namespace_configdb = (self.per_npu_configdb.values())[0]
namespace_configdb = (list(self.per_npu_configdb.values()))[0]
self.policers_db_info = namespace_configdb.get_table(self.POLICER)
else:
self.policers_db_info = self.configdb.get_table(self.POLICER)
Expand All @@ -199,19 +199,19 @@ def read_sessions_info(self):
# For multi-npu platforms we will read from any one of front asic namespace
# config db as the information should be same across all config db
if self.per_npu_configdb:
namespace_configdb = (self.per_npu_configdb.values())[0]
namespace_configdb = (list(self.per_npu_configdb.values()))[0]
self.sessions_db_info = namespace_configdb.get_table(self.CFG_MIRROR_SESSION_TABLE)
else:
self.sessions_db_info = self.configdb.get_table(self.CFG_MIRROR_SESSION_TABLE)
for key in self.sessions_db_info.keys():
for key in list(self.sessions_db_info.keys()):
if self.per_npu_statedb:
# For multi-npu platforms we will read from all front asic name space
# statedb as the monitor port will be differnt for each asic
# and it's status also might be different (ideally should not happen)
# We will store them as dict of 'asic' : value
self.sessions_db_info[key]["status"] = {}
self.sessions_db_info[key]["monitor_port"] = {}
for namespace_key, namespace_statedb in self.per_npu_statedb.iteritems():
for namespace_key, namespace_statedb in self.per_npu_statedb.items():
state_db_info = namespace_statedb.get_all(self.statedb.STATE_DB, "{}|{}".format(self.STATE_MIRROR_SESSION_TABLE, key))
self.sessions_db_info[key]["status"][namespace_key] = state_db_info.get("status", "inactive") if state_db_info else "error"
self.sessions_db_info[key]["monitor_port"][namespace_key] = state_db_info.get("monitor_port", "") if state_db_info else ""
Expand Down Expand Up @@ -367,7 +367,7 @@ def validate_actions(self, table_name, action_props):
# For multi-npu we will read using anyone statedb connector for front asic namespace.
# Same information should be there in all state DB's
# as it is static information about switch capability
namespace_statedb = (self.per_npu_statedb.values())[0]
namespace_statedb = (list(self.per_npu_statedb.values()))[0]
capability = namespace_statedb.get_all(self.statedb.STATE_DB, "{}|switch".format(self.SWITCH_CAPABILITY_TABLE))
else:
capability = self.statedb.get_all(self.statedb.STATE_DB, "{}|switch".format(self.SWITCH_CAPABILITY_TABLE))
Expand Down Expand Up @@ -417,7 +417,7 @@ def convert_ip(self, table_name, rule_idx, rule):
# FIXME: 0 is a valid protocol number, but openconfig seems to use it as a default value,
# so there isn't currently a good way to check if the user defined proto=0 or not.
if rule.ip.config.protocol:
if self.ip_protocol_map.has_key(rule.ip.config.protocol):
if rule.ip.config.protocol in self.ip_protocol_map:
rule_props["IP_PROTOCOL"] = self.ip_protocol_map[rule.ip.config.protocol]
else:
try:
Expand All @@ -430,14 +430,14 @@ def convert_ip(self, table_name, rule_idx, rule):

if rule.ip.config.source_ip_address:
source_ip_address = rule.ip.config.source_ip_address.encode("ascii")
if ipaddr.IPNetwork(source_ip_address).version == 4:
if ipaddress.ip_network(source_ip_address).version == 4:
rule_props["SRC_IP"] = source_ip_address
else:
rule_props["SRC_IPV6"] = source_ip_address

if rule.ip.config.destination_ip_address:
destination_ip_address = rule.ip.config.destination_ip_address.encode("ascii")
if ipaddr.IPNetwork(destination_ip_address).version == 4:
if ipaddress.ip_network(destination_ip_address).version == 4:
rule_props["DST_IP"] = destination_ip_address
else:
rule_props["DST_IPV6"] = destination_ip_address
Expand Down Expand Up @@ -579,17 +579,17 @@ def full_update(self):
be removed and new rules in that table will be installed.
:return:
"""
for key in self.rules_db_info.keys():
for key in list(self.rules_db_info.keys()):
if self.current_table is None or self.current_table == key[0]:
self.configdb.mod_entry(self.ACL_RULE, key, None)
# Program for per front asic namespace also if present
for namespace_configdb in self.per_npu_configdb.values():
for namespace_configdb in list(self.per_npu_configdb.values()):
namespace_configdb.mod_entry(self.ACL_RULE, key, None)


self.configdb.mod_config({self.ACL_RULE: self.rules_info})
# Program for per front asic namespace also if present
for namespace_configdb in self.per_npu_configdb.values():
for namespace_configdb in list(self.per_npu_configdb.values()):
namespace_configdb.mod_config({self.ACL_RULE: self.rules_info})

def incremental_update(self):
Expand All @@ -605,10 +605,10 @@ def incremental_update(self):
# update on dataplane ACLs, and only perform an incremental update on
# control plane ACLs.

new_rules = set(self.rules_info.iterkeys())
new_rules = set(self.rules_info.keys())
new_dataplane_rules = set()
new_controlplane_rules = set()
current_rules = set(self.rules_db_info.iterkeys())
current_rules = set(self.rules_db_info.keys())
current_dataplane_rules = set()
current_controlplane_rules = set()

Expand All @@ -630,15 +630,15 @@ def incremental_update(self):
for key in current_dataplane_rules:
self.configdb.mod_entry(self.ACL_RULE, key, None)
# Program for per-asic namespace also if present
for namespace_configdb in self.per_npu_configdb.values():
for namespace_configdb in list(self.per_npu_configdb.values()):
namespace_configdb.mod_entry(self.ACL_RULE, key, None)


# Add all new dataplane rules
for key in new_dataplane_rules:
self.configdb.mod_entry(self.ACL_RULE, key, self.rules_info[key])
# Program for per-asic namespace corresponding to front asic also if present.
for namespace_configdb in self.per_npu_configdb.values():
for namespace_configdb in list(self.per_npu_configdb.values()):
namespace_configdb.mod_entry(self.ACL_RULE, key, self.rules_info[key])

added_controlplane_rules = new_controlplane_rules.difference(current_controlplane_rules)
Expand All @@ -649,22 +649,22 @@ def incremental_update(self):
self.configdb.mod_entry(self.ACL_RULE, key, self.rules_info[key])
# Program for per-asic namespace corresponding to front asic also if present.
# For control plane ACL it's not needed but to keep all db in sync program everywhere
for namespace_configdb in self.per_npu_configdb.values():
for namespace_configdb in list(self.per_npu_configdb.values()):
namespace_configdb.mod_entry(self.ACL_RULE, key, self.rules_info[key])

for key in removed_controlplane_rules:
self.configdb.mod_entry(self.ACL_RULE, key, None)
# Program for per-asic namespace corresponding to front asic also if present.
# For control plane ACL it's not needed but to keep all db in sync program everywhere
for namespace_configdb in self.per_npu_configdb.values():
for namespace_configdb in list(self.per_npu_configdb.values()):
namespace_configdb.mod_entry(self.ACL_RULE, key, None)

for key in existing_controlplane_rules:
if cmp(self.rules_info[key], self.rules_db_info[key]) != 0:
self.configdb.set_entry(self.ACL_RULE, key, self.rules_info[key])
# Program for per-asic namespace corresponding to front asic also if present.
# For control plane ACL it's not needed but to keep all db in sync program everywhere
for namespace_configdb in self.per_npu_configdb.values():
for namespace_configdb in list(self.per_npu_configdb.values()):
namespace_configdb.set_entry(self.ACL_RULE, key, self.rules_info[key])

def delete(self, table=None, rule=None):
Expand All @@ -673,12 +673,12 @@ def delete(self, table=None, rule=None):
:param rule:
:return:
"""
for key in self.rules_db_info.iterkeys():
for key in self.rules_db_info.keys():
if not table or table == key[0]:
if not rule or rule == key[1]:
self.configdb.set_entry(self.ACL_RULE, key, None)
# Program for per-asic namespace corresponding to front asic also if present.
for namespace_configdb in self.per_npu_configdb.values():
for namespace_configdb in list(self.per_npu_configdb.values()):
namespace_configdb.set_entry(self.ACL_RULE, key, None)

def show_table(self, table_name):
Expand All @@ -690,7 +690,7 @@ def show_table(self, table_name):
header = ("Name", "Type", "Binding", "Description", "Stage")

data = []
for key, val in self.get_tables_db_info().iteritems():
for key, val in self.get_tables_db_info().items():
if table_name and key != table_name:
continue

Expand Down Expand Up @@ -728,7 +728,7 @@ def show_session(self, session_name):

erspan_data = []
span_data = []
for key, val in self.get_sessions_db_info().iteritems():
for key, val in self.get_sessions_db_info().items():
if session_name and key != session_name:
continue

Expand Down Expand Up @@ -756,7 +756,7 @@ def show_policer(self, policer_name):
header = ("Name", "Type", "Mode", "CIR", "CBS")

data = []
for key, val in self.get_policers_db_info().iteritems():
for key, val in self.get_policers_db_info().items():
if policer_name and key != policer_name:
continue

Expand Down Expand Up @@ -807,7 +807,7 @@ def pop_matches(val):
return matches

raw_data = []
for (tname, rid), val in self.get_rules_db_info().iteritems():
for (tname, rid), val in self.get_rules_db_info().items():

if table_name and table_name != tname:
continue
Expand Down
12 changes: 4 additions & 8 deletions clear/main.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,8 @@
import click
import configparser
import os
import subprocess

try:
# noinspection PyPep8Naming
import ConfigParser as configparser
except ImportError:
# noinspection PyUnresolvedReferences
import configparser
import click


# This is from the aliases example:
Expand Down Expand Up @@ -82,6 +77,7 @@ def get_routing_stack():
proc = subprocess.Popen(command,
stdout=subprocess.PIPE,
shell=True,
text=True,
stderr=subprocess.STDOUT)
stdout = proc.communicate()[0]
proc.wait()
Expand All @@ -99,7 +95,7 @@ def get_routing_stack():

def run_command(command, pager=False, return_output=False):
# Provide option for caller function to Process the output.
proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
proc = subprocess.Popen(command, shell=True, text=True, stdout=subprocess.PIPE)
if return_output:
return proc.communicate()
elif pager:
Expand Down
9 changes: 0 additions & 9 deletions config/aaa.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
#!/usr/bin/env python -u
# -*- coding: utf-8 -*-

import click

from swsssdk import ConfigDBConnector
import utilities_common.cli as clicommon

Expand Down Expand Up @@ -193,8 +189,3 @@ def delete(address):
config_db.connect()
config_db.set_entry('TACPLUS_SERVER', address, None)
tacacs.add_command(delete)


if __name__ == "__main__":
aaa()

15 changes: 7 additions & 8 deletions config/config_mgmt.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ def __init__(self, source="configDB", debug=False, allowTablesWithoutYang=True):

except Exception as e:
self.sysLog(doPrint=True, logLevel=syslog.LOG_ERR, msg=str(e))
raise(Exception('ConfigMgmt Class creation failed'))
raise Exception('ConfigMgmt Class creation failed')

return

Expand Down Expand Up @@ -168,7 +168,7 @@ def readConfigDBJson(self, source=CONFIG_DB_JSON_FILE):
self.configdbJsonIn = readJsonFile(source)
#self.sysLog(msg=type(self.configdbJsonIn))
if not self.configdbJsonIn:
raise(Exception("Can not load config from config DB json file"))
raise Exception("Can not load config from config DB json file")
self.sysLog(msg='Reading Input {}'.format(self.configdbJsonIn))

return
Expand Down Expand Up @@ -247,7 +247,7 @@ def __init__(self, source="configDB", debug=False, allowTablesWithoutYang=True):

except Exception as e:
self.sysLog(doPrint=True, logLevel=syslog.LOG_ERR, msg=str(e))
raise(Exception('ConfigMgmtDPB Class creation failed'))
raise Exception('ConfigMgmtDPB Class creation failed')

return

Expand Down Expand Up @@ -331,8 +331,7 @@ def _verifyAsicDB(self, db, ports, portMap, timeout):
if waitTime + 1 == timeout:
self.sysLog(syslog.LOG_CRIT, "!!! Critical Failure, Ports \
are not Deleted from ASIC DB, Bail Out !!!", doPrint=True)
raise(Exception("Ports are present in ASIC DB after {} secs".\
format(timeout)))
raise Exception("Ports are present in ASIC DB after {} secs".format(timeout))

except Exception as e:
self.sysLog(doPrint=True, logLevel=syslog.LOG_ERR, msg=str(e))
Expand Down Expand Up @@ -470,7 +469,7 @@ def _addPorts(self, portJson=dict(), loadDefConfig=True):
(configToLoad, ret) (tuple)[dict, bool]
'''
configToLoad = None
ports = portJson['PORT'].keys()
ports = list(portJson['PORT'].keys())
try:
self.sysLog(doPrint=True, msg='Start Port Addition')
self.sysLog(msg="addPorts Args portjson: {} loadDefConfig: {}".\
Expand Down Expand Up @@ -546,7 +545,7 @@ def _mergeItems(it1, it2):
pass
return

for it in D1.keys():
for it in list(D1.keys()):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
for it in list(D1.keys()):
for it in D1:

Copy link
Contributor Author

@jleveque jleveque Oct 3, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will not work. It would need to be:

for it, _ in D1:

I will not make a change like this in this PR. Plus, keeping .keys() makes it clear what the intention is.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It will work. I think you are talking about

for it, _ in D1.items():

In reply to: 499074240 [](ancestors = 499074240)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, you're correct. I misread this one. Everything started blending together after all these changes :)

I will go back through and do a cleanup pass in the future.

Copy link
Contributor Author

@jleveque jleveque Nov 16, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have opened a PR to clean up here.

# D2 has the key
if D2.get(it):
_mergeItems(D1[it], D2[it])
Expand Down Expand Up @@ -578,7 +577,7 @@ def _searchKeysInConfig(self, In, Out, skeys):
'''
found = False
if isinstance(In, dict):
for key in In.keys():
for key in list(In.keys()):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
for key in list(In.keys()):
for it in In:

Copy link
Contributor Author

@jleveque jleveque Oct 5, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will not work. It would need to be:

for it, _ in In:

I will not make a change like this in this PR. Plus, keeping .keys() makes it clear what the intention is.

for skey in skeys:
# pattern is very specific to current primary keys in
# config DB, may need to be updated later.
Expand Down
3 changes: 0 additions & 3 deletions config/console.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
#!/usr/bin/env python

import click

import utilities_common.cli as clicommon

#
Expand Down
4 changes: 2 additions & 2 deletions config/feature.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import click
import sys

import click
from utilities_common.cli import AbbreviationGroup, pass_db

#
Expand Down Expand Up @@ -42,7 +42,7 @@ def feature_autorestart(db, name, autorestart):
click.echo("Unable to retrieve feature table from Config DB.")
sys.exit(1)

if not feature_table.has_key(name):
if name not in feature_table:
click.echo("Unable to retrieve feature '{}'".format(name))
sys.exit(1)

Expand Down
Loading