Skip to content

Commit bd8d6c7

Browse files
authored
Convert to Python 3 (sonic-net#1128)
Conform syntax to support Python 3 using 2to3 tool and manual assessment
1 parent 8079558 commit bd8d6c7

File tree

119 files changed

+762
-802
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

119 files changed

+762
-802
lines changed

README.md

+8-9
Original file line numberDiff line numberDiff line change
@@ -24,13 +24,12 @@ Currently, this list of dependencies is as follows:
2424

2525
- libyang_1.0.73_amd64.deb
2626
- libyang-cpp_1.0.73_amd64.deb
27-
- python2-yang_1.0.73_amd64.deb
2827
- python3-yang_1.0.73_amd64.deb
29-
- redis_dump_load-1.1-py2-none-any.whl
30-
- swsssdk-2.0.1-py2-none-any.whl
31-
- sonic_py_common-1.0-py2-none-any.whl
32-
- sonic_config_engine-1.0-py2-none-any.whl
33-
- sonic_yang_mgmt-1.0-py2-none-any.whl
28+
- redis_dump_load-1.1-py3-none-any.whl
29+
- swsssdk-2.0.1-py3-none-any.whl
30+
- sonic_py_common-1.0-py3-none-any.whl
31+
- sonic_config_engine-1.0-py3-none-any.whl
32+
- sonic_yang_mgmt-1.0-py3-none-any.whl
3433
- sonic_yang_models-1.0-py3-none-any.whl
3534

3635

@@ -43,7 +42,7 @@ A convenient alternative is to let the SONiC build system configure a build envi
4342
4443
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
4544
```
46-
make NOJESSIE=1 NOSTRETCH=1 KEEP_SLAVE_ON=yes target/python-wheels/sonic_utilities-1.2-py2-none-any.whl
45+
make NOJESSIE=1 NOSTRETCH=1 KEEP_SLAVE_ON=yes target/python-wheels/sonic_utilities-1.2-py3-none-any.whl
4746
```
4847
4948
3. When the build finishes, your prompt will change to indicate you are inside the slave container. Change into the `src/sonic-utilities/` directory
@@ -56,13 +55,13 @@ A convenient alternative is to let the SONiC build system configure a build envi
5655
#### To build
5756
5857
```
59-
python2 setup.py bdist_wheel
58+
python3 setup.py bdist_wheel
6059
```
6160
6261
#### To run unit tests
6362
6463
```
65-
python2 setup.py test
64+
python3 setup.py test
6665
```
6766
6867

acl_loader/main.py

+27-27
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
#!/usr/bin/env python
1+
#!/usr/bin/env python3
22

33
import click
4-
import ipaddr
4+
import ipaddress
55
import json
66
import syslog
77

@@ -30,7 +30,7 @@ def error(msg):
3030

3131

3232
def deep_update(dst, src):
33-
for key, value in src.iteritems():
33+
for key, value in src.items():
3434
if isinstance(value, dict):
3535
node = dst.setdefault(key, {})
3636
deep_update(node, value)
@@ -182,7 +182,7 @@ def read_policers_info(self):
182182
# For multi-npu platforms we will read from any one of front asic namespace
183183
# config db as the information should be same across all config db
184184
if self.per_npu_configdb:
185-
namespace_configdb = (self.per_npu_configdb.values())[0]
185+
namespace_configdb = (list(self.per_npu_configdb.values()))[0]
186186
self.policers_db_info = namespace_configdb.get_table(self.POLICER)
187187
else:
188188
self.policers_db_info = self.configdb.get_table(self.POLICER)
@@ -199,19 +199,19 @@ def read_sessions_info(self):
199199
# For multi-npu platforms we will read from any one of front asic namespace
200200
# config db as the information should be same across all config db
201201
if self.per_npu_configdb:
202-
namespace_configdb = (self.per_npu_configdb.values())[0]
202+
namespace_configdb = (list(self.per_npu_configdb.values()))[0]
203203
self.sessions_db_info = namespace_configdb.get_table(self.CFG_MIRROR_SESSION_TABLE)
204204
else:
205205
self.sessions_db_info = self.configdb.get_table(self.CFG_MIRROR_SESSION_TABLE)
206-
for key in self.sessions_db_info.keys():
206+
for key in list(self.sessions_db_info.keys()):
207207
if self.per_npu_statedb:
208208
# For multi-npu platforms we will read from all front asic name space
209209
# statedb as the monitor port will be differnt for each asic
210210
# and it's status also might be different (ideally should not happen)
211211
# We will store them as dict of 'asic' : value
212212
self.sessions_db_info[key]["status"] = {}
213213
self.sessions_db_info[key]["monitor_port"] = {}
214-
for namespace_key, namespace_statedb in self.per_npu_statedb.iteritems():
214+
for namespace_key, namespace_statedb in self.per_npu_statedb.items():
215215
state_db_info = namespace_statedb.get_all(self.statedb.STATE_DB, "{}|{}".format(self.STATE_MIRROR_SESSION_TABLE, key))
216216
self.sessions_db_info[key]["status"][namespace_key] = state_db_info.get("status", "inactive") if state_db_info else "error"
217217
self.sessions_db_info[key]["monitor_port"][namespace_key] = state_db_info.get("monitor_port", "") if state_db_info else ""
@@ -367,7 +367,7 @@ def validate_actions(self, table_name, action_props):
367367
# For multi-npu we will read using anyone statedb connector for front asic namespace.
368368
# Same information should be there in all state DB's
369369
# as it is static information about switch capability
370-
namespace_statedb = (self.per_npu_statedb.values())[0]
370+
namespace_statedb = (list(self.per_npu_statedb.values()))[0]
371371
capability = namespace_statedb.get_all(self.statedb.STATE_DB, "{}|switch".format(self.SWITCH_CAPABILITY_TABLE))
372372
else:
373373
capability = self.statedb.get_all(self.statedb.STATE_DB, "{}|switch".format(self.SWITCH_CAPABILITY_TABLE))
@@ -417,7 +417,7 @@ def convert_ip(self, table_name, rule_idx, rule):
417417
# FIXME: 0 is a valid protocol number, but openconfig seems to use it as a default value,
418418
# so there isn't currently a good way to check if the user defined proto=0 or not.
419419
if rule.ip.config.protocol:
420-
if self.ip_protocol_map.has_key(rule.ip.config.protocol):
420+
if rule.ip.config.protocol in self.ip_protocol_map:
421421
rule_props["IP_PROTOCOL"] = self.ip_protocol_map[rule.ip.config.protocol]
422422
else:
423423
try:
@@ -430,14 +430,14 @@ def convert_ip(self, table_name, rule_idx, rule):
430430

431431
if rule.ip.config.source_ip_address:
432432
source_ip_address = rule.ip.config.source_ip_address.encode("ascii")
433-
if ipaddr.IPNetwork(source_ip_address).version == 4:
433+
if ipaddress.ip_network(source_ip_address).version == 4:
434434
rule_props["SRC_IP"] = source_ip_address
435435
else:
436436
rule_props["SRC_IPV6"] = source_ip_address
437437

438438
if rule.ip.config.destination_ip_address:
439439
destination_ip_address = rule.ip.config.destination_ip_address.encode("ascii")
440-
if ipaddr.IPNetwork(destination_ip_address).version == 4:
440+
if ipaddress.ip_network(destination_ip_address).version == 4:
441441
rule_props["DST_IP"] = destination_ip_address
442442
else:
443443
rule_props["DST_IPV6"] = destination_ip_address
@@ -579,17 +579,17 @@ def full_update(self):
579579
be removed and new rules in that table will be installed.
580580
:return:
581581
"""
582-
for key in self.rules_db_info.keys():
582+
for key in list(self.rules_db_info.keys()):
583583
if self.current_table is None or self.current_table == key[0]:
584584
self.configdb.mod_entry(self.ACL_RULE, key, None)
585585
# Program for per front asic namespace also if present
586-
for namespace_configdb in self.per_npu_configdb.values():
586+
for namespace_configdb in list(self.per_npu_configdb.values()):
587587
namespace_configdb.mod_entry(self.ACL_RULE, key, None)
588588

589589

590590
self.configdb.mod_config({self.ACL_RULE: self.rules_info})
591591
# Program for per front asic namespace also if present
592-
for namespace_configdb in self.per_npu_configdb.values():
592+
for namespace_configdb in list(self.per_npu_configdb.values()):
593593
namespace_configdb.mod_config({self.ACL_RULE: self.rules_info})
594594

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

608-
new_rules = set(self.rules_info.iterkeys())
608+
new_rules = set(self.rules_info.keys())
609609
new_dataplane_rules = set()
610610
new_controlplane_rules = set()
611-
current_rules = set(self.rules_db_info.iterkeys())
611+
current_rules = set(self.rules_db_info.keys())
612612
current_dataplane_rules = set()
613613
current_controlplane_rules = set()
614614

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

636636

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

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

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

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

670670
def delete(self, table=None, rule=None):
@@ -673,12 +673,12 @@ def delete(self, table=None, rule=None):
673673
:param rule:
674674
:return:
675675
"""
676-
for key in self.rules_db_info.iterkeys():
676+
for key in self.rules_db_info.keys():
677677
if not table or table == key[0]:
678678
if not rule or rule == key[1]:
679679
self.configdb.set_entry(self.ACL_RULE, key, None)
680680
# Program for per-asic namespace corresponding to front asic also if present.
681-
for namespace_configdb in self.per_npu_configdb.values():
681+
for namespace_configdb in list(self.per_npu_configdb.values()):
682682
namespace_configdb.set_entry(self.ACL_RULE, key, None)
683683

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

692692
data = []
693-
for key, val in self.get_tables_db_info().iteritems():
693+
for key, val in self.get_tables_db_info().items():
694694
if table_name and key != table_name:
695695
continue
696696

@@ -728,7 +728,7 @@ def show_session(self, session_name):
728728

729729
erspan_data = []
730730
span_data = []
731-
for key, val in self.get_sessions_db_info().iteritems():
731+
for key, val in self.get_sessions_db_info().items():
732732
if session_name and key != session_name:
733733
continue
734734

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

758758
data = []
759-
for key, val in self.get_policers_db_info().iteritems():
759+
for key, val in self.get_policers_db_info().items():
760760
if policer_name and key != policer_name:
761761
continue
762762

@@ -807,7 +807,7 @@ def pop_matches(val):
807807
return matches
808808

809809
raw_data = []
810-
for (tname, rid), val in self.get_rules_db_info().iteritems():
810+
for (tname, rid), val in self.get_rules_db_info().items():
811811

812812
if table_name and table_name != tname:
813813
continue

clear/main.py

+4-8
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,8 @@
1-
import click
1+
import configparser
22
import os
33
import subprocess
44

5-
try:
6-
# noinspection PyPep8Naming
7-
import ConfigParser as configparser
8-
except ImportError:
9-
# noinspection PyUnresolvedReferences
10-
import configparser
5+
import click
116

127

138
# This is from the aliases example:
@@ -82,6 +77,7 @@ def get_routing_stack():
8277
proc = subprocess.Popen(command,
8378
stdout=subprocess.PIPE,
8479
shell=True,
80+
text=True,
8581
stderr=subprocess.STDOUT)
8682
stdout = proc.communicate()[0]
8783
proc.wait()
@@ -99,7 +95,7 @@ def get_routing_stack():
9995

10096
def run_command(command, pager=False, return_output=False):
10197
# Provide option for caller function to Process the output.
102-
proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
98+
proc = subprocess.Popen(command, shell=True, text=True, stdout=subprocess.PIPE)
10399
if return_output:
104100
return proc.communicate()
105101
elif pager:

config/aaa.py

-9
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,4 @@
1-
#!/usr/bin/env python -u
2-
# -*- coding: utf-8 -*-
3-
41
import click
5-
62
from swsssdk import ConfigDBConnector
73
import utilities_common.cli as clicommon
84

@@ -193,8 +189,3 @@ def delete(address):
193189
config_db.connect()
194190
config_db.set_entry('TACPLUS_SERVER', address, None)
195191
tacacs.add_command(delete)
196-
197-
198-
if __name__ == "__main__":
199-
aaa()
200-

config/config_mgmt.py

+7-8
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ def __init__(self, source="configDB", debug=False, allowTablesWithoutYang=True):
7777

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

8282
return
8383

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

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

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

252252
return
253253

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

337336
except Exception as e:
338337
self.sysLog(doPrint=True, logLevel=syslog.LOG_ERR, msg=str(e))
@@ -470,7 +469,7 @@ def _addPorts(self, portJson=dict(), loadDefConfig=True):
470469
(configToLoad, ret) (tuple)[dict, bool]
471470
'''
472471
configToLoad = None
473-
ports = portJson['PORT'].keys()
472+
ports = list(portJson['PORT'].keys())
474473
try:
475474
self.sysLog(doPrint=True, msg='Start Port Addition')
476475
self.sysLog(msg="addPorts Args portjson: {} loadDefConfig: {}".\
@@ -546,7 +545,7 @@ def _mergeItems(it1, it2):
546545
pass
547546
return
548547

549-
for it in D1.keys():
548+
for it in list(D1.keys()):
550549
# D2 has the key
551550
if D2.get(it):
552551
_mergeItems(D1[it], D2[it])
@@ -578,7 +577,7 @@ def _searchKeysInConfig(self, In, Out, skeys):
578577
'''
579578
found = False
580579
if isinstance(In, dict):
581-
for key in In.keys():
580+
for key in list(In.keys()):
582581
for skey in skeys:
583582
# pattern is very specific to current primary keys in
584583
# config DB, may need to be updated later.

config/console.py

-3
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,4 @@
1-
#!/usr/bin/env python
2-
31
import click
4-
52
import utilities_common.cli as clicommon
63

74
#

config/feature.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
import click
21
import sys
32

3+
import click
44
from utilities_common.cli import AbbreviationGroup, pass_db
55

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

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

0 commit comments

Comments
 (0)