python3 - 2to3 + miscell obvious tweaks
authorThierry Parmentelat <thierry.parmentelat@inria.fr>
Thu, 28 Mar 2019 16:09:22 +0000 (17:09 +0100)
committerThierry Parmentelat <thierry.parmentelat@inria.fr>
Thu, 28 Mar 2019 16:09:22 +0000 (17:09 +0100)
112 files changed:
Makefile
clientbin/getNodes.py
clientbin/getRecord.py
clientbin/setRecord.py
clientbin/sfaadmin.py
clientbin/sfadump.py
clientbin/sfax509.py
clientbin/sfi.py
clientbin/sfiAddAttribute.py
clientbin/sfiAddLinks.py
clientbin/sfiAddSliver.py
clientbin/sfiDeleteAttribute.py
clientbin/sfiDeleteSliver.py
clientbin/sfiListLinks.py
clientbin/sfiListNodes.py
clientbin/sfiListSlivers.py
keyconvert/keyconvert.py
readme.py
setup.py
sfa.spec
sfa/client/candidates.py
sfa/client/client_helper.py
sfa/client/common.py
sfa/client/manifolduploader.py
sfa/client/multiclient.py
sfa/client/sfaadmin.py
sfa/client/sfaclientlib.py
sfa/client/sfaresetgids.py
sfa/client/sfascan.py
sfa/client/sfi.py
sfa/dummy/dummy_testbed_api.py
sfa/dummy/dummy_testbed_api_client.py
sfa/dummy/dummyaggregate.py
sfa/dummy/dummydriver.py
sfa/dummy/dummyshell.py
sfa/dummy/dummyslices.py
sfa/examples/miniclient.py
sfa/importer/__init__.py
sfa/iotlab/iotlabshell.py
sfa/managers/eucalyptus/euca_rspec_validator.py
sfa/managers/managerwrapper.py
sfa/managers/registry_manager.py
sfa/methods/GetGids.py
sfa/planetlab/nodemanager.py
sfa/planetlab/peers.py
sfa/planetlab/plaggregate.py
sfa/planetlab/pldriver.py
sfa/planetlab/plshell.py
sfa/planetlab/plslices.py
sfa/planetlab/plxrn.py
sfa/planetlab/vlink.py
sfa/rspecs/elements/element.py
sfa/rspecs/elements/versions/iotlabv1Node.py
sfa/rspecs/elements/versions/iotlabv1Sliver.py
sfa/rspecs/elements/versions/pgv2Services.py
sfa/rspecs/elements/versions/pgv2SliverType.py
sfa/rspecs/pg_rspec_converter.py
sfa/rspecs/rspec.py
sfa/rspecs/rspec_converter.py
sfa/rspecs/sfa_rspec_converter.py
sfa/rspecs/version.py
sfa/rspecs/version_manager.py
sfa/rspecs/versions/iotlabv1.py
sfa/rspecs/versions/ofeliav1.py
sfa/rspecs/versions/pgv2.py
sfa/rspecs/versions/sfav1.py
sfa/server/api_versions.py
sfa/server/interface.py
sfa/server/sfa-start.py
sfa/server/threadedserver.py
sfa/server/xmlrpcapi.py
sfa/storage/dbschema.py
sfa/storage/model.py
sfa/storage/record.py
sfa/trust/abac_credential.py
sfa/trust/certificate.py
sfa/trust/credential.py
sfa/trust/credential_factory.py
sfa/trust/gid.py
sfa/trust/sfaticket.py
sfa/trust/speaksfor_util.py
sfa/util/cache.py
sfa/util/callids.py
sfa/util/config.py
sfa/util/defaultdict.py
sfa/util/enumeration.py
sfa/util/method.py
sfa/util/prefixTree.py
sfa/util/printable.py
sfa/util/py23.py
sfa/util/sfalogging.py
sfa/util/sfatime.py
sfa/util/xml.py
sfatables/commands/Delete.py
sfatables/commands/Insert.py
sfatables/commands/List.py
sfatables/commands/moo.py
sfatables/pretty.py
sfatables/runtime.py
sfatables/xmlextension.py
sfatables/xmlrule.py
tests/client/testAggregate.py
tests/testAll.py
tests/testCert.py
tests/testHierarchy.py
tests/testInterfaces.py
tests/testKeypair.py
tests/testRights.py
tests/testXrn.py
tools/depgraph2dot.py
tools/py2depgraph.py
wsdl/sfa2wsdl.py

index 485f10a..1de2054 100644 (file)
--- a/Makefile
+++ b/Makefile
@@ -139,7 +139,7 @@ git:
 pypi: index.html
        setup.py sdist upload -r $(PYPI_TARGET)
        ssh $(PYPI_TARBALL_HOST) mkdir -p $(PYPI_TARBALL_TOPDIR)/$(VERSIONTAG)
-       rsync -av dist/sfa-$(VERSIONTAG).tar.gz $(PYPI_TARBALL_HOST):$(PYPI_TARBALL_TOPDIR)/$(VERSIONTAG)
+       rsync -ai dist/sfa-$(VERSIONTAG).tar.gz $(PYPI_TARBALL_HOST):$(PYPI_TARBALL_TOPDIR)/$(VERSIONTAG)
 
 # cleanup
 clean: readme-clean
@@ -183,7 +183,7 @@ LOCAL_RSYNC_EXCLUDES        += --exclude '*.pyc'
 LOCAL_RSYNC_EXCLUDES   += --exclude '*.png' --exclude '*.svg' --exclude '*.out'
 RSYNC_EXCLUDES         := --exclude .svn --exclude .git --exclude '*~' --exclude TAGS $(LOCAL_RSYNC_EXCLUDES)
 RSYNC_COND_DRY_RUN     := $(if $(findstring n,$(MAKEFLAGS)),--dry-run,)
-RSYNC                  := rsync -a -v $(RSYNC_COND_DRY_RUN) --no-owner $(RSYNC_EXCLUDES)
+RSYNC                  := rsync -ai $(RSYNC_COND_DRY_RUN) --no-owner $(RSYNC_EXCLUDES)
 
 CLIENTS = $(shell ls clientbin/*.py)
 
@@ -193,11 +193,7 @@ BINS =     ./config/sfa-config-tty ./systemd/sfa-setup.sh \
        $(CLIENTS)
 
 synclib: synccheck
-       +$(RSYNC) --relative ./sfa/ --exclude migrations $(SSHURL)/usr/lib\*/python2.\*/site-packages/
-synclib3: synccheck
        +$(RSYNC) --relative ./sfa/ --exclude migrations $(SSHURL)/usr/lib\*/python3.\*/site-packages/
-synclibdeb: synccheck
-       +$(RSYNC) --relative ./sfa/ --exclude migrations $(SSHURL)/usr/share/pyshared/
 syncmigrations:
        +$(RSYNC) ./sfa/storage/migrations/versions/*.py $(SSHURL)/usr/share/sfa/migrations/versions/
 syncbin: synccheck
@@ -236,7 +232,7 @@ sfa/util/{sfalogging,faults,genicode,enumeration,__init__}.py
 
 clientlibsync:
        @[ -d "$(CLIENTLIBTARGET)" ] || { echo "You need to set the make variable CLIENTLIBTARGET"; exit 1; }
-       rsync -av --relative $(CLIENTLIBFILES) $(CLIENTLIBTARGET)
+       rsync -ai --relative $(CLIENTLIBFILES) $(CLIENTLIBTARGET)
 
 #################### convenience, for debugging only
 # make +foo : prints the value of $(foo)
index 5cbf5a3..aa0a4b1 100644 (file)
@@ -1,4 +1,4 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python3
 
 import sys
 import os
@@ -36,10 +36,10 @@ def print_dict(rdict, options, counter=1):
 
     if not isinstance(rdict, dict):
         raise "%s not a dict" % rdict
-    for (key, value) in rdict.iteritems():
+    for (key, value) in rdict.items():
         if isinstance(value, StringType):
             if (attributes and key in attributes) or not attributes:
-                print tab * counter + "%s: %s" % (key, value)
+                print(tab * counter + "%s: %s" % (key, value))
         elif isinstance(value, list):
             for listitem in value:
                 if isinstance(listitem, dict):
@@ -50,12 +50,12 @@ def print_dict(rdict, options, counter=1):
     if counter == 1 or print_children:
         for (key, listitem) in lists:
             if isinstance(listitem, dict):
-                print tab * (counter - 1) + key
+                print(tab * (counter - 1) + key)
                 print_dict(listitem, options, counter + 1)
     elif not attributes or (attributes and 'children' in attributes):
         keys = set([key for (key, listitem) in lists])
         if keys:
-            print tab * (counter) + "(children: %s)" % (",".join(keys))
+            print(tab * (counter) + "(children: %s)" % (",".join(keys)))
 
 
 #
@@ -67,14 +67,14 @@ def main():
     parser = create_parser()
     (options, args) = parser.parse_args()
     if not options.infile:
-        print "RSpec file not specified"
+        print("RSpec file not specified")
         return
 
     rspec = RSpec()
     try:
         rspec.parseFile(options.infile)
     except:
-        print "Error reading rspec file"
+        print("Error reading rspec file")
 
     if options.tag:
         tag_name = options.tag
@@ -92,4 +92,4 @@ if __name__ == '__main__':
         main()
     except Exception as e:
         raise
-        print e
+        print(e)
index 97d1794..8af2bf6 100755 (executable)
@@ -1,4 +1,4 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python3
 
 """
 Filters/Prints record objects
@@ -24,11 +24,11 @@ def create_parser():
     description = """getRecord will parse a supplied (via stdin) record and print all values or key/values, and filter results based on a given key or set of keys."""
     parser = OptionParser(usage=usage, description=description)
     parser.add_option("-d", "--debug", dest="DEBUG", action="store_true",
-                      default=False,  help="record file path")
+                      default=False, help="record file path")
     parser.add_option("-k", "--key", dest="withkey", action="store_true",
-                      default=False,  help="print SSH keys and certificates")
+                      default=False, help="print SSH keys and certificates")
     parser.add_option("-p", "--plinfo", dest="plinfo", action="store_true",
-                      default=False,  help="print PlanetLab specific internal fields")
+                      default=False, help="print PlanetLab specific internal fields")
 
     return parser
 
@@ -38,18 +38,18 @@ def printRec(record_dict, filters, options):
     if len(filters):
         for filter in filters:
             if options.DEBUG:
-                print "Filtering on %s" % filter
+                print("Filtering on %s" % filter)
             line += "%s: %s\n" % (filter,
                                   printVal(record_dict.get(filter, None)))
-        print line
+        print(line)
     else:
         # print the wole thing
-        for (key, value) in record_dict.iteritems():
+        for (key, value) in record_dict.items():
             if (not options.withkey and key in ('gid', 'keys')) or\
                     (not options.plinfo and key == 'pl_info'):
                 continue
             line += "%s: %s\n" % (key, printVal(value))
-        print line
+        print(line)
 
 
 # fix the iteratable values
@@ -74,7 +74,7 @@ def main():
 
     if options.DEBUG:
         pprint(record.toxml())
-        print "#####################################################"
+        print("#####################################################")
 
     printRec(record_dict, args, options)
 
@@ -82,7 +82,7 @@ if __name__ == '__main__':
     try:
         main()
     except ExpatError as e:
-        print "RecordError.  Is your record valid XML?"
-        print e
+        print("RecordError.  Is your record valid XML?")
+        print(e)
     except Exception as e:
-        print e
+        print(e)
index 742cf95..493400c 100755 (executable)
@@ -1,4 +1,4 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python3
 
 """
 Updates record objects
@@ -58,7 +58,7 @@ def replaceDict(newval, recordDict, options):
     Replaces field in dict
     """
     # Check type of old field matches type of new field
-    for (key, val) in newval.iteritems():
+    for (key, val) in newval.items():
         recordDict[key] = val
 
 
@@ -66,7 +66,7 @@ def modDict(newval, recordDict, options):
     """
     Checks type of existing field, addends new field
     """
-    for (key, val) in newval.iteritems():
+    for (key, val) in newval.items():
         if (type(recordDict[key]) == list):
             if (type(val) == list):
                 recordDict[key] = recordDict[key] + val
@@ -98,7 +98,7 @@ def main():
     if args:
         editDict(args, record_dict, options)
     if options.DEBUG:
-        print "New Record:\n%s" % record_dict
+        print("New Record:\n%s" % record_dict)
 
     record.parse_dict(record_dict)
     s = record.toxml()
@@ -108,4 +108,4 @@ if __name__ == '__main__':
     try:
         main()
     except Exception as e:
-        print e
+        print(e)
index ce6930b..eb34ece 100755 (executable)
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 
 from sfa.client.sfaadmin import SfaAdmin
 
index c87d193..9d4afa4 100755 (executable)
@@ -61,10 +61,10 @@ def save_gid(gid):
     filename = lastpart + ".gid"
 
     if os.path.exists(filename):
-        print filename, ": already exists... skipping"
+        print(filename, ": already exists... skipping")
         return
 
-    print filename, ": extracting gid of", hrn
+    print(filename, ": extracting gid of", hrn)
 
     gid.save_to_file(filename, save_parents=True)
 
@@ -87,18 +87,18 @@ def extract_gids(cred, extract_parents):
 
 def verify_input_object(obj, kind, options):
     if options.trusted_roots:
-        print "CHECKING...",
+        print("CHECKING...", end=' ')
         message = "against [" + (" + ".join(options.trusted_roots)) + "]"
         try:
             if kind == 'credential':
-                print "verify", message,
+                print("verify", message, end=' ')
                 obj.verify(options.trusted_roots)
             elif kind in ('certificate', 'gid'):
-                print "verify_chain", message,
+                print("verify_chain", message, end=' ')
                 obj.verify_chain(options.trusted_roots)
-            print "--> OK"
+            print("--> OK")
         except Exception as inst:
-            print "--> KO", type(inst).__name__
+            print("--> KO", type(inst).__name__)
 
 
 def handle_input(filename, options):
@@ -107,24 +107,24 @@ def handle_input(filename, options):
     # dump methods current do 'print' so let's go this road for now
     if kind == "certificate":
         cert = Certificate(filename=filename)
-        print '--------------------', filename, 'IS A', kind
+        print('--------------------', filename, 'IS A', kind)
         cert.dump(show_extensions=options.show_extensions)
         verify_input_object(cert, kind, options)
     elif kind == "credential":
         cred = Credential(filename=filename)
-        print '--------------------', filename, 'IS A', kind
+        print('--------------------', filename, 'IS A', kind)
         cred.dump(dump_parents=options.dump_parents, show_xml=options.show_xml)
         if options.extract_gids:
-            print '--------------------', filename, 'embedded GIDs'
+            print('--------------------', filename, 'embedded GIDs')
             extract_gids(cred, extract_parents=options.dump_parents)
         verify_input_object(cred, kind, options)
     elif kind == "gid":
         gid = GID(filename=filename)
-        print '--------------------', filename, 'IS A', kind
+        print('--------------------', filename, 'IS A', kind)
         gid.dump(dump_parents=options.dump_parents)
         verify_input_object(gid, kind, options)
     else:
-        print "%s: unknown filekind '%s'" % (filename, kind)
+        print("%s: unknown filekind '%s'" % (filename, kind))
 
 
 def main():
index 0d64808..22c2614 100755 (executable)
@@ -1,6 +1,6 @@
 #!/usr/bin/env python
 
-from __future__ import print_function
+
 
 # something like openssl x509
 # but when used on a gid file we show all the parts
index 3778c5e..51cf963 100755 (executable)
@@ -1,4 +1,4 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python3
 
 # sfi -- slice-based facility interface
 
index 89f4a7c..186828c 100755 (executable)
@@ -29,7 +29,7 @@ if command.opts.infile:
         f.close()
 
     for name in attrs:
-        print >> sys.stderr, name, attrs[name]
+        print(name, attrs[name], file=sys.stderr)
         for value in attrs[name]:
             if not nodes:
                 try:
@@ -45,4 +45,4 @@ if command.opts.infile:
                         logger.log_exc(
                             "sfiAddAttribute FAILED on node %s: %s=%s" % (node, name, value))
 
-    print rspec.toxml()
+    print(rspec.toxml())
index f3792b6..3f08553 100755 (executable)
@@ -16,7 +16,7 @@ command.add_linkfile_option()
 command.prep()
 
 if not command.opts.linkfile:
-    print "Missing link list -- exiting"
+    print("Missing link list -- exiting")
     command.parser.print_help()
     sys.exit(1)
 
@@ -30,7 +30,7 @@ else:
     outfile = sys.stdout
 ad_rspec = RSpec(infile)
 links = open(command.opts.linkfile).read().split('\n')
-link_tuples = map(lambda x: tuple(x.split()), links)
+link_tuples = [tuple(x.split()) for x in links]
 
 version_manager = VersionManager()
 try:
@@ -44,5 +44,5 @@ try:
 except:
     logger.log_exc("sfiAddLinks FAILED with links %s" % links)
     sys.exit(1)
-print >>outfile, request_rspec.toxml()
+print(request_rspec.toxml(), file=outfile)
 sys.exit(0)
index 93bb500..8431bd7 100755 (executable)
@@ -16,7 +16,7 @@ command.add_nodefile_option()
 command.prep()
 
 if not command.opts.nodefile:
-    print "Missing node list -- exiting"
+    print("Missing node list -- exiting")
     command.parser.print_help()
     sys.exit(1)
 
@@ -42,5 +42,5 @@ try:
 except:
     logger.log_exc("sfiAddSliver failed with nodes %s" % nodes)
     sys.exit(1)
-print >>outfile, request_rspec.toxml()
+print(request_rspec.toxml(), file=outfile)
 sys.exit(0)
index d0ae0b4..7e566f7 100755 (executable)
@@ -29,7 +29,7 @@ if command.opts.infile:
         f.close()
 
     for name in attrs:
-        print >> sys.stderr, name, attrs[name]
+        print(name, attrs[name], file=sys.stderr)
         for value in attrs[name]:
             if not nodes:
                 try:
@@ -46,4 +46,4 @@ if command.opts.infile:
                         logger.log_exc(
                             "sfiDeleteAttribute FAILED on node %s: %s=%s" % (node, name, value))
 
-    print rspec.toxml()
+    print(rspec.toxml())
index 8669ad6..ff3b9de 100755 (executable)
@@ -25,6 +25,6 @@ if command.opts.infile:
     try:
         slivers = [{'hostname': node} for node in nodes]
         rspec.version.remove_slivers(slivers)
-        print rspec.toxml()
+        print(rspec.toxml())
     except:
         logger.log_exc("sfiDeleteSliver FAILED with nodes %s" % nodes)
index 67e603d..d84b942 100755 (executable)
@@ -19,4 +19,4 @@ if command.opts.infile:
     for link in links:
         ifname1 = Xrn(link['interface1']['component_id']).get_leaf()
         ifname2 = Xrn(link['interface2']['component_id']).get_leaf()
-        print "%s %s" % (ifname1, ifname2)
+        print("%s %s" % (ifname1, ifname2))
index 13377c9..b14b982 100755 (executable)
@@ -25,4 +25,4 @@ if command.opts.infile:
         if node.get('component_id'):
             hostname = xrn_to_hostname(node['component_id'])
         if hostname:
-            print hostname
+            print(hostname)
index 9fdd1c0..32da6b5 100755 (executable)
@@ -21,17 +21,17 @@ if command.opts.infile:
     if command.opts.showatt:
         defaults = rspec.version.get_default_sliver_attributes()
         if defaults:
-            print "ALL NODES"
+            print("ALL NODES")
             for (name, value) in defaults:
-                print "  %s: %s" % (name, value)
+                print("  %s: %s" % (name, value))
 
     for node in nodes:
         hostname = None
         if node.get('component_id'):
             hostname = xrn_to_hostname(node['component_id'])
         if hostname:
-            print hostname
+            print(hostname)
             if command.opts.showatt:
                 atts = rspec.version.get_sliver_attributes(hostname)
                 for (name, value) in atts:
-                    print "  %s: %s" % (name, value)
+                    print("  %s: %s" % (name, value))
index 143a8c8..2effcb6 100755 (executable)
@@ -108,7 +108,7 @@ def convert(fin, fout):
 
 if __name__ == "__main__":
     if len(sys.argv) != 3:
-        print "Usage: %s <input-file> <output-file>"
+        print("Usage: %s <input-file> <output-file>")
         sys.exit(1)
 
     fin = sys.argv[1]
index dd2ed9c..29d992a 100755 (executable)
--- a/readme.py
+++ b/readme.py
@@ -1,6 +1,6 @@
 #!/usr/bin/env python
 
-from __future__ import print_function
+
 
 from argparse import ArgumentParser
 
index dff8e81..6b624df 100755 (executable)
--- a/setup.py
+++ b/setup.py
@@ -1,6 +1,6 @@
 #!/usr/bin/env python
 
-from __future__ import print_function
+
 
 """
 Installation script for the sfa module
index 41318d3..afa927a 100644 (file)
--- a/sfa.spec
+++ b/sfa.spec
@@ -29,27 +29,27 @@ BuildRequires: make
 Requires: util-linux-ng
 # for the registry
 Requires: postgresql >= 8.2, postgresql-server >= 8.2
-Requires: postgresql-python
-Requires: python2-psycopg2
-Requires: python2-sqlalchemy
-Requires: python2-migrate
+Requires: postgresql3-python
+Requires: python3-psycopg2
+Requires: python3-sqlalchemy
+Requires: python3-migrate
 # and of course the bulk of it
 Requires: sfa-common
 
 %package common
 Summary: Python libraries for SFA, generic implementation derived from PlanetLab
 Group: Applications/System
-Requires: python
-Requires: pyOpenSSL
-Requires: m2crypto
-Requires: python2-dateutil
-Requires: python2-lxml
-%if "%{distro}" == "Fedora" && "%{distrorelease}" <= "27"
-Requires: python-ZSI
-%else
-Requires: python2-zsi
-%endif
-Requires: libxslt-python
+Requires: python3
+Requires: python3-pyOpenSSL
+Requires: python3-m2crypto
+Requires: python3-dateutil
+Requires: python3-lxml
+%if "%{distro}" == "Fedora" && "%{distrorelease}" <= "27"
+Requires: python-ZSI
+%else
+Requires: python2-zsi
+%endif
+Requires: libxslt-python
 Requires: xmlsec1-openssl-devel
 
 %package client
index c36e199..d332fc4 100644 (file)
@@ -1,4 +1,4 @@
-from __future__ import print_function
+
 
 # utility to match command-line args to names
 
index 82b5f19..8098319 100644 (file)
@@ -55,7 +55,7 @@ def sfa_to_pg_users_arg(users):
     new_users = []
     fields = ['urn', 'keys']
     for user in users:
-        new_user = dict([item for item in user.items()
+        new_user = dict([item for item in list(user.items())
                          if item[0] in fields])
         new_users.append(new_user)
     return new_users
index f27098d..4d019f3 100644 (file)
@@ -1,6 +1,6 @@
 # a few utilities common to sfi and sfaadmin
 
-from __future__ import print_function
+
 
 
 def optparse_listvalue_callback(option, opt, value, parser):
@@ -106,7 +106,7 @@ def terminal_render(records, options):
         if type not in grouped_by_type:
             grouped_by_type[type] = []
         grouped_by_type[type].append(record)
-    group_types = grouped_by_type.keys()
+    group_types = list(grouped_by_type.keys())
     group_types.sort()
     for type in group_types:
         group = grouped_by_type[type]
index 60bed0c..f40e2aa 100755 (executable)
@@ -52,7 +52,7 @@ class ManifoldUploader:
 
     def username(self):
         if not self._username:
-            self._username = raw_input("Enter your manifold username: ")
+            self._username = input("Enter your manifold username: ")
         return self._username
 
     def password(self):
@@ -64,7 +64,7 @@ class ManifoldUploader:
 
     def platform(self):
         if not self._platform:
-            self._platform = raw_input(
+            self._platform = input(
                 "Enter your manifold platform [%s]: " % DEFAULT_PLATFORM)
             if self._platform.strip() == "":
                 self._platform = DEFAULT_PLATFORM
@@ -72,7 +72,7 @@ class ManifoldUploader:
 
     def url(self):
         if not self._url:
-            self._url = raw_input(
+            self._url = input(
                 "Enter the URL for your manifold API [%s]: " % DEFAULT_URL)
             if self._url.strip() == "":
                 self._url = DEFAULT_URL
@@ -146,7 +146,7 @@ class ManifoldUploader:
             self.logger.info("  V2 Update returned code %s and error >>%s<<" % (
                 retcod2['code'], retcod2['description']))
             self.logger.debug("****** full retcod2")
-            for k, v in retcod2.items():
+            for k, v in list(retcod2.items()):
                 self.logger.debug("**** %s: %s" % (k, v))
             return False
         except Exception as e:
index 3939994..ad6f357 100644 (file)
@@ -1,9 +1,9 @@
-from __future__ import print_function
+
 
 import threading
 import traceback
 import time
-from Queue import Queue
+from queue import Queue
 from sfa.util.sfalogging import logger
 
 
@@ -105,7 +105,7 @@ if __name__ == '__main__':
 
     def e(name, n, sleep=1):
         nums = []
-        for i in range(n, n + 3) + ['n', 'b']:
+        for i in list(range(n, n + 3)) + ['n', 'b']:
             print("%s: 1 + %s:" % (name, i))
             nums.append(i + 1)
             time.sleep(sleep)
index edfa9c0..4cf7722 100755 (executable)
@@ -1,8 +1,8 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python3
 
 # pylint: disable=c0111, c0103, w0402, w0622
 
-from __future__ import print_function
+
 
 import os
 import sys
@@ -514,7 +514,7 @@ class SfaAdmin:
 
     # returns (name,class) or (None,None)
     def find_category(self, input):
-        full_name = Candidates(SfaAdmin.CATEGORIES.keys()).only_match(input)
+        full_name = Candidates(list(SfaAdmin.CATEGORIES.keys())).only_match(input)
         if not full_name:
             return (None, None)
         return (full_name, SfaAdmin.CATEGORIES[full_name])
@@ -528,7 +528,7 @@ class SfaAdmin:
         for c in categories:
             cls = SfaAdmin.CATEGORIES[c]
             print("==================== category=%s" % c)
-            names = cls.__dict__.keys()
+            names = list(cls.__dict__.keys())
             names.sort()
             for name in names:
                 method = cls.__dict__[name]
@@ -587,7 +587,7 @@ class SfaAdmin:
         cmd_kwds = vars(opts)
 
         # dont overrride meth
-        for k, v in cmd_kwds.items():
+        for k, v in list(cmd_kwds.items()):
             if v is None:
                 del cmd_kwds[k]
 
index cac4d1f..5557b95 100644 (file)
@@ -3,7 +3,7 @@
 a minimal library for writing "lightweight" SFA clients
 """
 
-from __future__ import print_function
+
 
 # xxx todo
 # this library should probably check for the expiration date of the various
@@ -226,7 +226,7 @@ class SfaClientBootstrap:
 # when leaving this empty on the mac, result can't seem to be loaded in
 # keychain..
     def my_pkcs12_produce(self, filename):
-        password = raw_input("Enter password for p12 certificate: ")
+        password = input("Enter password for p12 certificate: ")
         openssl_command = ['openssl', 'pkcs12', "-export"]
         openssl_command += ["-password", "pass:{}".format(password)]
         openssl_command += ["-inkey", self.private_key_filename()]
index dbf548b..2466bcf 100644 (file)
@@ -1,6 +1,6 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python3
+
 
-from __future__ import print_function
 
 from argparse import ArgumentParser
 
index 8869ae5..3b07697 100644 (file)
@@ -1,4 +1,4 @@
-from __future__ import print_function
+
 
 import sys
 import os.path
@@ -6,7 +6,7 @@ import pickle
 import time
 import socket
 import traceback
-from urlparse import urlparse
+from urllib.parse import urlparse
 
 try:
     import pygraphviz
@@ -65,7 +65,7 @@ class VersionCache:
             logger.debug("Cannot load version cache, restarting from scratch")
             self.url2version = {}
         logger.debug("loaded version cache with %d entries %s" % (len(self.url2version),
-                                                                  self.url2version.keys()))
+                                                                  list(self.url2version.keys())))
 
     def save(self):
         try:
@@ -87,7 +87,7 @@ class VersionCache:
         entries = len(self.url2version)
         print("version cache from file %s has %d entries" %
               (self.filename, entries))
-        key_values = self.url2version.items()
+        key_values = list(self.url2version.items())
 
         def old_first(kv1, kv2): return int(kv1[1][0] - kv2[1][0])
         key_values.sort(old_first)
@@ -312,16 +312,16 @@ class Scanner:
                     logger.info(
                         "<EMPTY GetVersion(); offline or cannot authenticate>")
                 else:
-                    for (k, v) in version.iteritems():
+                    for (k, v) in version.items():
                         if not isinstance(v, dict):
                             logger.debug("\r\t%s:%s" % (k, v))
                         else:
                             logger.debug(k)
-                            for (k1, v1) in v.iteritems():
+                            for (k1, v1) in v.items():
                                 logger.debug("\r\t\t%s:%s" % (k1, v1))
                 # proceed with neighbours
                 if 'peers' in version:
-                    for (next_name, next_url) in version['peers'].iteritems():
+                    for (next_name, next_url) in version['peers'].items():
                         next_interface = Interface(
                             next_url, mentioned_in=interface.url())
                         # locate or create node in graph
@@ -342,7 +342,7 @@ class Scanner:
             for node in graph.nodes():
                 interface = node2interface.get(node, None)
                 if interface:
-                    for (k, v) in interface.get_layout().iteritems():
+                    for (k, v) in interface.get_layout().items():
                         node.attr[k] = v
                 else:
                     logger.error("MISSED interface with node %s" % node)
index 20b878e..ac2a553 100644 (file)
@@ -5,7 +5,7 @@ this module is also used in sfascan
 
 # pylint: disable=c0111, c0413
 
-from __future__ import print_function
+
 
 import sys
 sys.path.append('.')
@@ -310,7 +310,7 @@ def declare_command(args_string, example, aliases=None):
 
 
 def remove_none_fields(record):
-    none_fields = [k for (k, v) in record.items() if v is None]
+    none_fields = [k for (k, v) in list(record.items()) if v is None]
     for k in none_fields:
         del record[k]
 
index 697cda5..9bbf9c8 100644 (file)
@@ -1,4 +1,4 @@
-import SimpleXMLRPCServer
+import xmlrpc.server
 import time
 
 dummy_api_addr = ("localhost", 8080)
@@ -14,9 +14,9 @@ for i in range(1, 11):
 slices_list = []
 for i in range(1, 3):
     slice = {'slice_name': 'slice' + str(i),
-             'user_ids': range(i, 4, 2),
+             'user_ids': list(range(i, 4, 2)),
              'slice_id': i,
-             'node_ids': range(i, 10, 2),
+             'node_ids': list(range(i, 10, 2)),
              'enabled': True,
              'expires': int(time.time()) + 60 * 60 * 24 * 30}
     slices_list.append(slice)
@@ -37,7 +37,7 @@ def FilterList(myfilter, mylist):
     result = []
     result.extend(mylist)
     for item in mylist:
-        for key in myfilter.keys():
+        for key in list(myfilter.keys()):
             if 'ids' in key:
                 pass
             else:
@@ -109,7 +109,7 @@ def AddNode(node):
     global DB
     if not isinstance(node, dict):
         return False
-    for key in node.keys():
+    for key in list(node.keys()):
         if key not in ['hostname', 'type']:
             return False
     node['node_id'] = DB['node_index']
@@ -122,7 +122,7 @@ def AddSlice(slice):
     global DB
     if not isinstance(slice, dict):
         return False
-    for key in slice.keys():
+    for key in list(slice.keys()):
         if key not in ['slice_name', 'user_ids', 'node_ids', 'enabled', 'expires']:
             return False
     slice['slice_id'] = DB['slice_index']
@@ -136,7 +136,7 @@ def AddUser(user):
     global DB
     if not isinstance(user, dict):
         return False
-    for key in user.keys():
+    for key in list(user.keys()):
         if key not in ['user_name', 'email', 'keys']:
             return False
     user['user_id'] = DB['user_index']
@@ -152,7 +152,7 @@ def AddUserKey(param):
     try:
         for user in DB['users_list']:
             if param['user_id'] == user['user_id']:
-                if 'keys' in user.keys():
+                if 'keys' in list(user.keys()):
                     user['keys'].append(param['key'])
                 else:
                     user['keys'] = [param['key']]
@@ -297,7 +297,7 @@ def UpdateNode(param):
     try:
         for node in DB['nodes_list']:
             if param['node_id'] == node['node_id']:
-                for key in param['fields'].keys():
+                for key in list(param['fields'].keys()):
                     if key in ['hostname', 'type']:
                         node[key] = param['fields'][key]
                 return True
@@ -313,7 +313,7 @@ def UpdateSlice(param):
     try:
         for slice in DB['slices_list']:
             if param['slice_id'] == slice['slice_id']:
-                for key in param['fields'].keys():
+                for key in list(param['fields'].keys()):
                     if key in ['slice_name']:
                         slice[key] = param['fields'][key]
                 return True
@@ -329,7 +329,7 @@ def UpdateUser(param):
     try:
         for user in DB['users_list']:
             if param['user_id'] == user['user_id']:
-                for key in param['fields'].keys():
+                for key in list(param['fields'].keys()):
                     if key in ['user_name', 'email']:
                         user[key] = param['fields'][key]
                 return True
@@ -339,7 +339,7 @@ def UpdateUser(param):
 
 
 # Instantiate the XMLRPC server
-dummy_api_server = SimpleXMLRPCServer.SimpleXMLRPCServer(dummy_api_addr)
+dummy_api_server = xmlrpc.server.SimpleXMLRPCServer(dummy_api_addr)
 
 # RPC functions registration
 dummy_api_server.register_function(GetTestbedInfo)
index 2c3d363..9df5144 100644 (file)
@@ -1,4 +1,4 @@
-from __future__ import print_function
+
 
 from datetime import datetime
 import time
index 2e6fc5b..fcdca5d 100644 (file)
@@ -1,4 +1,4 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python3
 from sfa.util.xrn import Xrn, hrn_to_urn, urn_to_hrn
 from sfa.util.sfatime import utcparse, datetime_to_string
 from sfa.util.sfalogging import logger
@@ -46,7 +46,7 @@ class DummyAggregate:
 
         # sort slivers by node id
         slice_nodes = []
-        if 'node_ids' in slice.keys():
+        if 'node_ids' in list(slice.keys()):
             slice_nodes = self.driver.shell.GetNodes(
                 {'node_ids': slice['node_ids']})
         for node in slice_nodes:
@@ -99,7 +99,7 @@ class DummyAggregate:
         users = []
         user_ids = []
         for slice in slices:
-            if 'user_ids' in slice.keys():
+            if 'user_ids' in list(slice.keys()):
                 user_ids.extend(slice['user_ids'])
         if user_ids:
             users = self.driver.shell.GetUsers({'user_ids': user_ids})
@@ -121,7 +121,7 @@ class DummyAggregate:
             slice['node_ids'] = node_ids
         nodes_dict = self.get_slice_nodes(slice, options)
         slivers = []
-        for node in nodes_dict.values():
+        for node in list(nodes_dict.values()):
             node.update(slice)
             sliver_hrn = '%s.%s-%s' % (self.driver.hrn,
                                        slice['slice_id'], node['node_id'])
index 01bc8d0..44bc767 100644 (file)
@@ -389,7 +389,7 @@ class DummyDriver (Driver):
         # hard-wire the code for slice/user for now, could be smarter if needed
         if subject_type == 'slice' and target_type == 'user' and relation_name == 'researcher':
             subject = self.shell.GetSlices({'slice_id': subject_id})[0]
-            if 'user_ids' not in subject.keys():
+            if 'user_ids' not in list(subject.keys()):
                 subject['user_ids'] = []
             current_target_ids = subject['user_ids']
             add_target_ids = list(
index d647cb5..e330d28 100644 (file)
@@ -1,6 +1,6 @@
 import sys
 import socket
-from urlparse import urlparse
+from urllib.parse import urlparse
 
 from sfa.util.sfalogging import logger
 from sfa.util.py23 import xmlrpc_client
index 6c0f8ae..579d7cb 100644 (file)
@@ -10,7 +10,7 @@ from sfa.storage.model import SliverAllocation
 
 from sfa.dummy.dummyxrn import DummyXrn, hrn_to_dummy_slicename
 
-MAXINT = 2L**31 - 1
+MAXINT = 2**31 - 1
 
 
 class DummySlices:
@@ -73,10 +73,10 @@ class DummySlices:
         all_nodes = self.driver.shell.GetNodes()
         requested_slivers = []
         for node in all_nodes:
-            if node['hostname'] in slivers.keys():
+            if node['hostname'] in list(slivers.keys()):
                 requested_slivers.append(node['node_id'])
 
-        if 'node_ids' not in slice.keys():
+        if 'node_ids' not in list(slice.keys()):
             slice['node_ids'] = []
         nodes = self.driver.shell.GetNodes({'node_ids': slice['node_ids']})
         current_slivers = [node['node_id'] for node in nodes]
index 2366c78..c588b5f 100755 (executable)
@@ -3,7 +3,7 @@
 # this is designed to use a totally empty new directory
 # so we demonstrate how to bootstrap the whole thing
 
-from __future__ import print_function
+
 
 # init logging on console
 import logging
@@ -70,7 +70,7 @@ def get_version(url):
     server_proxy = bootstrap.server_proxy_simple(url)
     server_version = server_proxy.GetVersion()
     print("miniclient: GetVersion at %s returned:" % (url))
-    for (k, v) in server_version.iteritems():
+    for (k, v) in server_version.items():
         print("miniclient: \tversion[%s]=%s" % (k, truncate(v)))
 
 # version_dict = {'type': 'SFA', 'version': '1', }
index 90e15e4..8981793 100644 (file)
@@ -1,4 +1,4 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python3
 
 # pylint: disable=c0111, w1201, w0622
 
index 3b9f993..605fa98 100644 (file)
@@ -6,7 +6,7 @@ from iotlabcli import auth
 from iotlabcli import rest
 from iotlabcli import helpers
 from iotlabcli import experiment
-from urllib2 import HTTPError
+from urllib.error import HTTPError
 
 
 class IotLABShell(object):
index 34fbf73..ff52169 100755 (executable)
@@ -1,6 +1,6 @@
 #!/usr/bin/env python
 
-from __future__ import print_function
+
 
 import sys
 import os
index 77af9bf..326b6b6 100644 (file)
@@ -1,4 +1,4 @@
-from types import ModuleType, ClassType
+from types import ModuleType
 
 from sfa.util.faults import SfaNotImplemented, SfaAPIError
 from sfa.util.sfalogging import logger
@@ -9,20 +9,21 @@ from sfa.util.sfalogging import logger
 class ManagerWrapper:
     """
     This class acts as a wrapper around an SFA interface manager module, but
-    can be used with any python module. The purpose of this class is raise a 
-    SfaNotImplemented exception if someone attempts to use an attribute 
+    can be used with any python module. The purpose of this class is raise a
+    SfaNotImplemented exception if someone attempts to use an attribute
     (could be a callable) thats not available in the library by checking the
-    library using hasattr. This helps to communicate better errors messages 
-    to the users and developers in the event that a specifiec operation 
+    library using hasattr. This helps to communicate better errors messages
+    to the users and developers in the event that a specifiec operation
     is not implemented by a libarary and will generally be more helpful than
-    the standard AttributeError         
+    the standard AttributeError
     """
 
     def __init__(self, manager, interface, config):
         if isinstance(manager, ModuleType):
             # old-fashioned module implementation
             self.manager = manager
-        elif isinstance(manager, ClassType):
+        # if it's a class
+        elif isinstance(manager, type):
             # create an instance; we don't pass the api in argument as it is passed
             # to the actual method calls anyway
             self.manager = manager(config)
index 74d271a..208cea7 100644 (file)
@@ -1,11 +1,11 @@
 # pylint: disable=c0111, w1202
 
-from __future__ import print_function
+
 
 # for get_key_from_incoming_ip
 import tempfile
 import os
-import commands
+import subprocess
 
 from sfa.util.faults import (
     RecordNotFound, AccountNotEnabled, PermissionError, MissingAuthority,
@@ -86,7 +86,7 @@ class RegistryManager:
     # The GENI GetVersion call
     def GetVersion(self, api, options):
         peers = {hrn: interface.get_url()
-                 for (hrn, interface) in api.registries.iteritems()
+                 for (hrn, interface) in api.registries.items()
                  if hrn != api.hrn}
         xrn = Xrn(api.hrn, type='authority')
         return version_core({'interface': 'registry',
@@ -191,7 +191,7 @@ class RegistryManager:
         xrn_dict = {}
         registries = api.registries
         tree = prefixTree()
-        registry_hrns = registries.keys()
+        registry_hrns = list(registries.keys())
         tree.load(registry_hrns)
         for xrn in xrns:
             registry_hrn = tree.best_match(urn_to_hrn(xrn)[0])
@@ -279,7 +279,7 @@ class RegistryManager:
         # the longest matching prefix
         hrn, type = urn_to_hrn(xrn)
         registries = api.registries
-        registry_hrns = registries.keys()
+        registry_hrns = list(registries.keys())
         tree = prefixTree()
         tree.load(registry_hrns)
         registry_hrn = tree.best_match(hrn)
@@ -682,7 +682,7 @@ class RegistryManager:
         all_commands = [scp_key_command, scp_gid_command]
 
         for command in all_commands:
-            (status, output) = commands.getstatusoutput(command)
+            (status, output) = subprocess.getstatusoutput(command)
             if status:
                 raise Exception(output)
 
index 197e522..1e2349f 100644 (file)
@@ -41,7 +41,7 @@ class GetGids(Method):
 
         allowed_fields = ['hrn', 'type', 'gid']
         for record in records:
-            for key in record.keys():
+            for key in list(record.keys()):
                 if key not in allowed_fields:
                     del(record[key])
         return records
index db8bc0f..2e755d9 100644 (file)
@@ -1,5 +1,5 @@
 import tempfile
-import commands
+import subprocess
 import os
 
 
@@ -40,11 +40,11 @@ print s.%(method)s%(args)s"""  % locals()
             f.close()
             # make the file executeable
             chmod_cmd = "/bin/chmod 775 %(filename)s" % locals()
-            (status, output) = commands.getstatusoutput(chmod_cmd)
+            (status, output) = subprocess.getstatusoutput(chmod_cmd)
 
             # execute the commad as a slice with root NM privs
             cmd = 'su - %(sfa_slice)s -c "%(python)s %(scriptname)s"' % locals()
-            (status, output) = commands.getstatusoutput(cmd)
+            (status, output) = subprocess.getstatusoutput(cmd)
             return (status, output)
         finally:
             os.unlink(filename)
index 8c676f3..083ea9d 100644 (file)
@@ -18,7 +18,7 @@ def get_peer(pldriver, hrn):
     peers = pldriver.shell.GetPeers(
         {}, ['peer_id', 'peername', 'shortname', 'hrn_root'])
     for peer_record in peers:
-        names = [name.lower() for name in peer_record.values()
+        names = [name.lower() for name in list(peer_record.values())
                  if isinstance(name, StringType)]
         if site_authority in names:
             peer = peer_record['shortname']
index a5a3a0e..69ea426 100644 (file)
@@ -1,4 +1,4 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python3
 from collections import defaultdict
 from sfa.util.xrn import Xrn, hrn_to_urn, urn_to_hrn, get_authority, get_leaf
 from sfa.util.sfatime import utcparse, datetime_to_string
@@ -215,7 +215,7 @@ class PlAggregate:
         pltags_dict = self.get_pltags_by_node_id(slice)
         nodes_dict = self.get_slice_nodes(slice, options)
         slivers = []
-        for node in nodes_dict.values():
+        for node in list(nodes_dict.values()):
             node.update(slice)
             # slice-global tags
             node['slice-tags'] = pltags_dict['slice-global']
@@ -281,7 +281,7 @@ class PlAggregate:
         ]
         # only doing this because protogeni rspec needs
         # to advertise available initscripts
-        rspec_node['pl_initscripts'] = pl_initscripts.values()
+        rspec_node['pl_initscripts'] = list(pl_initscripts.values())
         # add site/interface info to nodes.
         # assumes that sites, interfaces and tags have already been prepared.
         if site['longitude'] and site['latitude']:
index 6a917a4..0a21a8e 100644 (file)
@@ -136,7 +136,7 @@ class PlDriver (Driver):
 
         elif type == 'slice':
             acceptable_fields = ['url', 'instantiation', 'name', 'description']
-            for key in pl_record.keys():
+            for key in list(pl_record.keys()):
                 if key not in acceptable_fields:
                     pl_record.pop(key)
             slices = self.shell.GetSlices(
@@ -234,7 +234,7 @@ class PlDriver (Driver):
             #    this. I copied the field names from UpdatePerson.py...
             update_fields = {}
             all_fields = new_sfa_record
-            for key in all_fields.keys():
+            for key in list(all_fields.keys()):
                 if key in ['first_name', 'last_name', 'title', 'email',
                            'password', 'phone', 'url', 'bio', 'accepted_aup',
                            'enabled']:
index f544f7a..1dd1773 100644 (file)
@@ -1,7 +1,7 @@
 import sys
-import xmlrpclib
+import xmlrpc.client
 import socket
-from urlparse import urlparse
+from urllib.parse import urlparse
 
 from sfa.util.sfalogging import logger
 
@@ -93,7 +93,7 @@ class PlShell:
             import ssl
             ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS)
             ssl_context.verify_mode = ssl.CERT_NONE
-            self.proxy = xmlrpclib.ServerProxy(
+            self.proxy = xmlrpc.client.ServerProxy(
                 url, verbose=False, allow_none=True, context=ssl_context)
 
     def __getattr__(self, name):
index e868acd..3f6ef7d 100644 (file)
@@ -11,7 +11,7 @@ from sfa.planetlab.plxrn import (PlXrn, hrn_to_pl_slicename, xrn_to_hostname,
                                  top_auth, hash_loginbase)
 from sfa.storage.model import SliverAllocation
 
-MAXINT = 2L**31 - 1
+MAXINT = 2**31 - 1
 
 
 class PlSlices:
@@ -51,7 +51,7 @@ class PlSlices:
 
         # Build up list of keys
         key_ids = set()
-        for person in all_persons.values():
+        for person in list(all_persons.values()):
             key_ids.update(person['key_ids'])
         key_ids = list(key_ids)
         # Get user account keys
@@ -92,17 +92,13 @@ class PlSlices:
             sliver_attributes = []
 
             if node is not None:
-                for sliver_attribute in filter(
-                        lambda a: a['node_id'] == node['node_id'],
-                        slice_tags):
+                for sliver_attribute in [a for a in slice_tags if a['node_id'] == node['node_id']]:
                     sliver_attributes.append(sliver_attribute['tagname'])
                     attributes.append({'tagname': sliver_attribute['tagname'],
                                        'value': sliver_attribute['value']})
 
             # set nodegroup slice attributes
-            for slice_tag in filter(
-                    lambda a: a['nodegroup_id'] in node['nodegroup_ids'],
-                    slice_tags):
+            for slice_tag in [a for a in slice_tags if a['nodegroup_id'] in node['nodegroup_ids']]:
                 # Do not set any nodegroup slice attributes for
                 # which there is at least one sliver attribute
                 # already set.
@@ -110,9 +106,7 @@ class PlSlices:
                     attributes.append({'tagname': slice_tag['tagname'],
                                        'value': slice_tag['value']})
 
-            for slice_tag in filter(
-                    lambda a: a['node_id'] is None,
-                    slice_tags):
+            for slice_tag in [a for a in slice_tags if a['node_id'] is None]:
                 # Do not set any global slice attributes for
                 # which there is at least one sliver attribute
                 # already set.
@@ -237,7 +231,7 @@ class PlSlices:
         current_slivers = [node['hostname'] for node in nodes]
 
         # remove nodes not in rspec
-        deleted_nodes = list(set(current_slivers).difference(slivers.keys()))
+        deleted_nodes = list(set(current_slivers).difference(list(slivers.keys())))
 
         # add nodes from rspec
         added_nodes = list(set(slivers.keys()).difference(current_slivers))
index f9cf63c..3df3994 100644 (file)
@@ -1,4 +1,4 @@
-from __future__ import print_function
+
 
 # specialized Xrn class for PlanetLab
 import re
index 75c19ce..3a45fc6 100644 (file)
@@ -109,7 +109,7 @@ class VLink:
         my_ip = VLink.get_virt_ip(link['interface1'], link['interface2'])
         remote_ip = VLink.get_virt_ip(link['interface2'], link['interface1'])
         net = VLink.get_virt_net(link)
-        bw = format_tc_rate(long(link['capacity']))
+        bw = format_tc_rate(int(link['capacity']))
         return (link['interface2']['id'], ipaddr, bw, my_ip, remote_ip, net)
 
     @staticmethod
index 21f0949..7dcfa00 100644 (file)
@@ -8,7 +8,7 @@ class Element(dict):
         self.element = element
         dict.__init__(self, dict.fromkeys(self.fields))
         if not keys:
-            keys = fields.keys()
+            keys = list(fields.keys())
         for key in keys:
             if key in fields:
                 self[key] = fields[key]
index 99b5dea..e64368a 100644 (file)
@@ -55,8 +55,8 @@ class Iotlabv1Node:
                 ['ssh ' + ldap_username + '@' + site + '.iotlab.info'
                  for site in sites_set]
             network_elem.set('ssh',
-                             unicode(iotlab_network_dict['ssh']))
-            network_elem.set('login', unicode(iotlab_network_dict['login']))
+                             str(iotlab_network_dict['ssh']))
+            network_elem.set('login', str(iotlab_network_dict['login']))
 
     @staticmethod
     def add_nodes(xml, nodes, rspec_content_type=None):
index 110b932..2cc2bf2 100644 (file)
@@ -1,4 +1,4 @@
-from __future__ import print_function
+
 
 from sfa.rspecs.elements.element import Element
 from sfa.rspecs.elements.sliver import Sliver
@@ -39,7 +39,7 @@ class Iotlabv1Sliver:
                     attrib_elem = xml.add_element(
                         '{%s}info' % self.namespaces['flack'])
                     attrib_dict = eval(tag['value'])
-                    for (key, value) in attrib_dict.items():
+                    for (key, value) in list(attrib_dict.items()):
                         attrib_elem.set(key, value)
 
     @staticmethod
index 61e73ae..f2b1573 100644 (file)
@@ -16,7 +16,7 @@ class PGv2Services:
             child_elements = {'install': Install.fields,
                               'execute': Execute.fields,
                               'login': Login.fields}
-            for (name, fields) in child_elements.items():
+            for (name, fields) in list(child_elements.items()):
                 child = service.get(name)
                 if not child:
                     continue
index 9a5e1d7..dfad2cc 100644 (file)
@@ -43,7 +43,7 @@ class PGv2SliverType:
                     '{%s}info' % self.namespaces['flack'])
                 try:
                     attrib_dict = eval(tag['value'])
-                    for (key, value) in attrib_dict.items():
+                    for (key, value) in list(attrib_dict.items()):
                         attrib_elem.set(key, value)
                 except Exception as e:
                     logger.warning(
index 0fff41e..c0eaad7 100755 (executable)
@@ -1,5 +1,5 @@
-#!/usr/bin/env python2
-from __future__ import print_function
+#!/usr/bin/env python3
+
 
 from lxml import etree
 from sfa.util.xrn import Xrn, urn_to_hrn
@@ -64,7 +64,7 @@ class PGRSpecConverter:
         nodes_with_slivers = pg_rspec.version.get_nodes_with_slivers()
         i = 1
         for pg_node in pg_nodes_elements:
-            attribs = dict(pg_node.items())
+            attribs = dict(list(pg_node.items()))
             attribs['id'] = 'n' + str(i)
 
             node_element = network_element.add_element('node')
index fdd9c95..1677991 100755 (executable)
@@ -1,6 +1,6 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python3
+
 
-from __future__ import print_function
 
 from datetime import datetime, timedelta
 
index 49555c8..0c05857 100755 (executable)
@@ -1,6 +1,6 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python3
+
 
-from __future__ import print_function
 
 from sfa.rspecs.pg_rspec_converter import PGRSpecConverter
 from sfa.rspecs.sfa_rspec_converter import SfaRSpecConverter
index 297d371..3b51db5 100755 (executable)
@@ -1,6 +1,6 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python3
+
 
-from __future__ import print_function
 
 from sfa.util.xrn import hrn_to_urn
 from sfa.rspecs.rspec import RSpec
index d2ef55e..b5e7b77 100644 (file)
@@ -1,4 +1,4 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python3
 from sfa.util.sfalogging import logger
 
 
index e71c7ca..b4daf42 100644 (file)
@@ -1,4 +1,4 @@
-from __future__ import print_function
+
 
 import os
 from sfa.util.faults import InvalidRSpec, UnsupportedRSpecVersion
index 5d4383c..ceb67ee 100644 (file)
@@ -1,4 +1,4 @@
-from __future__ import print_function
+
 
 from copy import deepcopy
 
index c38dee3..719cc47 100755 (executable)
@@ -1,6 +1,6 @@
 #!/usr/bin/env python
 # -*- coding: utf-8 -*-
-from __future__ import print_function
+
 
 from copy import deepcopy
 from lxml import etree
index d9ca683..17a18e0 100644 (file)
@@ -1,4 +1,4 @@
-from __future__ import print_function
+
 
 from copy import deepcopy
 from sfa.util.xrn import Xrn
index 588e3c0..9b77837 100644 (file)
@@ -1,4 +1,4 @@
-from __future__ import print_function
+
 
 from copy import deepcopy
 from lxml import etree
index 6e58492..722be75 100644 (file)
@@ -35,13 +35,13 @@ class ApiVersions:
 
     def get_versions(self):
         versions = {}
-        for value in self.xml.todict().values():
+        for value in list(self.xml.todict().values()):
             if not value:
                 continue
             if isinstance(value, list):
                 for item in value:
                     if isinstance(item, dict) and \
-                       set(ApiVersions.required_fields).issubset(item.keys()) and \
+                       set(ApiVersions.required_fields).issubset(list(item.keys())) and \
                        item['version'] != '' and item['url'] != '':
                         versions[str(item['version'])] = item['url']
         return versions
index 093dcb8..104eefc 100644 (file)
@@ -63,11 +63,11 @@ class Interfaces(dict):
         # load config file
         required_fields = set(self.default_fields.keys())
         self.interface_info = XML(conf_file).todict()
-        for value in self.interface_info.values():
+        for value in list(self.interface_info.values()):
             if isinstance(value, list):
                 for record in value:
                     if isinstance(record, dict) and \
-                            required_fields.issubset(record.keys()):
+                            required_fields.issubset(list(record.keys())):
                         hrn, address, port = record[
                             'hrn'], record['addr'], record['port']
                         # sometime this is called at a very early stage with no config loaded
index cb14adb..5c3a2e4 100755 (executable)
@@ -1,4 +1,4 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python3
 #
 # PlanetLab SFA implementation
 #
@@ -60,7 +60,7 @@ def install_peer_certs(server_key_file, server_cert_file):
     api = SfaApi(key_file=server_key_file, cert_file=server_cert_file)
     registries = Registries()
     aggregates = Aggregates()
-    interfaces = dict(registries.items() + aggregates.items())
+    interfaces = dict(list(registries.items()) + list(aggregates.items()))
     gids_current = api.auth.trusted_cert_list
     hrns_current = [gid.get_hrn() for gid in gids_current]
     hrns_expected = set([hrn for hrn in interfaces])
index 5d07e69..d5c47bf 100644 (file)
@@ -10,10 +10,10 @@ import sys
 import socket
 import traceback
 import threading
-from Queue import Queue
-import SocketServer
-import BaseHTTPServer
-import SimpleXMLRPCServer
+from queue import Queue
+import socketserver
+import http.server
+import xmlrpc.server
 from OpenSSL import SSL
 
 from sfa.util.sfalogging import logger
@@ -86,7 +86,7 @@ def verify_callback(conn, x509, err, depth, preverify):
 # handler
 
 
-class SecureXMLRpcRequestHandler(SimpleXMLRPCServer.SimpleXMLRPCRequestHandler):
+class SecureXMLRpcRequestHandler(xmlrpc.server.SimpleXMLRPCRequestHandler):
     """Secure XML-RPC request handler class.
 
     It it very similar to SimpleXMLRPCRequestHandler but it uses HTTPS for transporting XML data.
@@ -151,7 +151,7 @@ class SecureXMLRpcRequestHandler(SimpleXMLRPCServer.SimpleXMLRPCRequestHandler):
 # Taken from the web (XXX find reference). Implements an HTTPS xmlrpc server
 
 
-class SecureXMLRPCServer(BaseHTTPServer.HTTPServer, SimpleXMLRPCServer.SimpleXMLRPCDispatcher):
+class SecureXMLRPCServer(http.server.HTTPServer, xmlrpc.server.SimpleXMLRPCDispatcher):
 
     def __init__(self, server_address, HandlerClass, key_file, cert_file, logRequests=True):
         """
@@ -170,11 +170,11 @@ class SecureXMLRPCServer(BaseHTTPServer.HTTPServer, SimpleXMLRPCServer.SimpleXML
         HandlerClass.cache = Cache()
         # for compatibility with python 2.4 (centos53)
         if sys.version_info < (2, 5):
-            SimpleXMLRPCServer.SimpleXMLRPCDispatcher.__init__(self)
+            xmlrpc.server.SimpleXMLRPCDispatcher.__init__(self)
         else:
-            SimpleXMLRPCServer.SimpleXMLRPCDispatcher.__init__(
+            xmlrpc.server.SimpleXMLRPCDispatcher.__init__(
                 self, True, None)
-        SocketServer.BaseServer.__init__(self, server_address, HandlerClass)
+        socketserver.BaseServer.__init__(self, server_address, HandlerClass)
         ctx = SSL.Context(SSL.SSLv23_METHOD)
         ctx.use_privatekey_file(key_file)
         ctx.use_certificate_file(cert_file)
@@ -202,7 +202,7 @@ class SecureXMLRPCServer(BaseHTTPServer.HTTPServer, SimpleXMLRPCServer.SimpleXML
     def _dispatch(self, method, params):
         logger.debug("SecureXMLRPCServer._dispatch, method=%s" % method)
         try:
-            return SimpleXMLRPCServer.SimpleXMLRPCDispatcher._dispatch(self, method, params)
+            return xmlrpc.server.SimpleXMLRPCDispatcher._dispatch(self, method, params)
         except:
             # can't use format_exc() as it is not available in jython yet
             # (even in trunk).
@@ -244,7 +244,7 @@ class SecureXMLRPCServer(BaseHTTPServer.HTTPServer, SimpleXMLRPCServer.SimpleXML
 # for each request, requests are processed by of pool of reusable threads.
 
 
-class ThreadPoolMixIn(SocketServer.ThreadingMixIn):
+class ThreadPoolMixIn(socketserver.ThreadingMixIn):
     """
     use a thread pool instead of a new thread on every request
     """
@@ -277,7 +277,7 @@ class ThreadPoolMixIn(SocketServer.ThreadingMixIn):
         obtain request from queue instead of directly from server socket
         """
         while True:
-            SocketServer.ThreadingMixIn.process_request_thread(
+            socketserver.ThreadingMixIn.process_request_thread(
                 self, *self.requests.get())
 
     def handle_request(self):
index f3d4e68..54fb745 100644 (file)
@@ -2,7 +2,7 @@
 # SFA XML-RPC and SOAP interfaces
 #
 
-import string
+from importlib import import_module
 
 # SOAP support is optional
 try:
@@ -26,15 +26,20 @@ from sfa.util.py23 import xmlrpc_client
 # avoiding
 # [#x7F-#x84], [#x86-#x9F], [#xFDD0-#xFDDF]
 
-invalid_codepoints = range(0x0, 0x8) + [0xB, 0xC] + range(0xE, 0x1F)
-# broke with f24, somehow we get a unicode as an incoming string to be translated
-str_xml_escape_table = string.maketrans("".join((chr(x) for x in invalid_codepoints)),
-                                        "?" * len(invalid_codepoints))
+invalid_codepoints = list(range(0x0, 0x8)) + [0xB, 0xC] + list(range(0xE, 0x1F))
+# broke with f24, somehow we get a unicode
+# as an incoming string to be translated
+str_xml_escape_table = \
+    str.maketrans("".join((chr(x) for x in invalid_codepoints)),
+                  "?" * len(invalid_codepoints))
 # loosely inspired from
-# http://stackoverflow.com/questions/1324067/how-do-i-get-str-translate-to-work-with-unicode-strings
-unicode_xml_escape_table = { invalid : u"?" for invalid in invalid_codepoints}
+# http://stackoverflow.com/questions/1324067/
+# how-do-i-get-str-translate-to-work-with-unicode-strings
+unicode_xml_escape_table = \
+    {invalid: "?" for invalid in invalid_codepoints}
 
-def xmlrpclib_escape(s, replace = string.replace):
+
+def xmlrpclib_escape(s, replace=str.replace):
     """
     xmlrpclib does not handle invalid 7-bit control characters. This
     function augments xmlrpclib.escape, which by default only replaces
@@ -66,16 +71,15 @@ def xmlrpclib_dump(self, value, write):
 
     # Use our escape function
     args = [self, value, write]
-    if isinstance(value, (str, unicode)):
+    if isinstance(value, str):
         args.append(xmlrpclib_escape)
 
     try:
         # Try for an exact match first
         f = self.dispatch[type(value)]
     except KeyError:
-        raise
         # Try for an isinstance() match
-        for Type, f in self.dispatch.iteritems():
+        for Type, f in self.dispatch.items():
             if isinstance(value, Type):
                 f(*args)
                 return
@@ -83,6 +87,7 @@ def xmlrpclib_dump(self, value, write):
     else:
         f(*args)
 
+
 # You can't hide from me!
 # Note: not quite  sure if this will still cause
 # the expected behaviour under python3
@@ -102,8 +107,7 @@ class XmlrpcApi:
         self.source = None
 
         # flat list of method names
-        self.methods_module = methods_module = __import__(
-            methods, fromlist=[methods])
+        self.methods_module = methods_module = import_module(methods)
         self.methods = methods_module.all
 
     def callable(self, method):
@@ -117,8 +121,8 @@ class XmlrpcApi:
         # Get new instance of method
         try:
             classname = method.split(".")[-1]
-            module = __import__(self.methods_module.__name__ +
-                                "." + method, globals(), locals(), [classname])
+            module = import_module(
+                self.methods_module.__name__ + "." + method)
             callablemethod = getattr(module, classname)(self)
             return getattr(module, classname)(self)
         except (ImportError, AttributeError):
index 1bed5e0..785d91b 100644 (file)
@@ -1,4 +1,4 @@
-from __future__ import print_function
+
 
 import sys
 import traceback
index 6cb5f1d..a2e3bd4 100644 (file)
@@ -55,7 +55,7 @@ class AlchemyObj(Record):
         self._i = iter(object_mapper(self).columns)
         return self
 
-    def next(self):
+    def __next__(self):
         n = self._i.next().name
         return n, getattr(self, n)
 
@@ -529,7 +529,7 @@ def make_record_dict(record_dict):
 def make_record_xml(xml_str):
     xml = XML(xml_str)
     xml_dict = xml.todict()
-    logger.info("load from xml, keys=%s" % xml_dict.keys())
+    logger.info("load from xml, keys=%s" % list(xml_dict.keys()))
     return make_record_dict(xml_dict)
 
 ####################
@@ -581,7 +581,7 @@ def augment_with_sfa_builtins(local_record):
     # search in map according to record type
     type_map = augment_map.get(local_record.type, {})
     # use type-dep. map to do the job
-    for (field_name, attribute) in type_map.items():
+    for (field_name, attribute) in list(type_map.items()):
         # get related objects
         related_records = getattr(local_record, attribute, [])
         hrns = [r.hrn for r in related_records]
index e869704..ac391a1 100644 (file)
@@ -1,4 +1,4 @@
-from __future__ import print_function
+
 
 from sfa.util.sfatime import utcparse, datetime_to_string
 from datetime import datetime
@@ -49,14 +49,14 @@ class Record:
 
         def exclude(k, v):
             return k.startswith('_') or isinstance(v, exclude_types)
-        keys = [k for k, v in d.items() if not exclude(k, v)]
+        keys = [k for k, v in list(d.items()) if not exclude(k, v)]
         return {k: d[k] for k in keys}
 
     def toxml(self):
         return self.save_as_xml()
 
     def load_from_dict(self, d):
-        for (k, v) in d.iteritems():
+        for (k, v) in d.items():
             # experimental
             if isinstance(v, StringType) and v.lower() in ['true']:
                 v = True
@@ -68,7 +68,7 @@ class Record:
     # for this purpose only, we need the subclasses to define 'fields' as either
     # a list or a dictionary
     def fields(self):
-        fields = self.__dict__.keys()
+        fields = list(self.__dict__.keys())
         return fields
 
     def save_as_xml(self):
index edf21c9..3534c00 100644 (file)
@@ -21,7 +21,7 @@
 # IN THE WORK.
 #----------------------------------------------------------------------
 
-from __future__ import print_function
+
 
 from sfa.trust.credential import Credential, append_sub, DEFAULT_CREDENTIAL_LIFETIME
 from sfa.util.sfalogging import logger
index fb515e5..cdad52a 100644 (file)
@@ -45,7 +45,7 @@
 #
 
 
-from __future__ import print_function
+
 
 import functools
 import os
@@ -521,7 +521,7 @@ class Certificate:
                 req = OpenSSL.crypto.X509Req()
                 reqSubject = req.get_subject()
                 if isinstance(subject, dict):
-                    for key in reqSubject.keys():
+                    for key in list(reqSubject.keys()):
                         setattr(reqSubject, key, subject[key])
                 else:
                     setattr(reqSubject, "CN", subject)
@@ -548,7 +548,7 @@ class Certificate:
         req = OpenSSL.crypto.X509Req()
         subj = req.get_subject()
         if isinstance(name, dict):
-            for key in name.keys():
+            for key in list(name.keys()):
                 setattr(subj, key, name[key])
         else:
             setattr(subj, "CN", name)
@@ -937,7 +937,7 @@ class Certificate:
         return triples
 
     def get_data_names(self):
-        return self.data.keys()
+        return list(self.data.keys())
 
     def get_all_datas(self):
         triples = self.get_extensions()
index 301fefe..307ed95 100644 (file)
@@ -27,7 +27,7 @@
 # privileges to an object gid
 ##
 
-from __future__ import print_function
+
 
 import os
 import os.path
index fb8206a..07cd6da 100644 (file)
@@ -21,7 +21,7 @@
 # IN THE WORK.
 #----------------------------------------------------------------------
 
-from __future__ import print_function
+
 
 from sfa.util.sfalogging import logger
 from sfa.trust.credential import Credential
index 799b1f4..7387902 100644 (file)
@@ -25,7 +25,7 @@
 # descendant of the certificate class.
 ##
 
-from __future__ import print_function
+
 
 import uuid
 
index 2c1e38b..1401b64 100644 (file)
@@ -24,7 +24,7 @@
 # implements SFA tickets
 #
 
-from __future__ import print_function
+
 
 from sfa.trust.certificate import Certificate
 from sfa.trust.gid import GID
@@ -142,7 +142,7 @@ class SfaTicket(Certificate):
             gidObject.dump(8, dump_parents)
 
         print("  attributes:")
-        for attrname in self.get_attributes().keys():
+        for attrname in list(self.get_attributes().keys()):
             print("        ", attrname, self.get_attributes()[attrname])
 
         print("       rspec:")
index 12ee8d0..7019e3c 100644 (file)
@@ -21,7 +21,7 @@
 # IN THE WORK.
 #----------------------------------------------------------------------
 
-from __future__ import print_function
+
 
 import datetime
 from dateutil import parser as du_parser, tz as du_tz
index 175968b..cb795fd 100644 (file)
@@ -1,7 +1,7 @@
 #
 # This module implements general purpose caching system
 #
-from __future__ import with_statement
+
 import time
 import threading
 import pickle
index 3206886..7adc170 100644 (file)
@@ -1,4 +1,4 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python3
 
 import threading
 import time
@@ -63,7 +63,7 @@ class _call_ids_impl (dict):
     def _purge(self):
         now = time.time()
         o_keys = []
-        for (k, v) in self.iteritems():
+        for (k, v) in self.items():
             if (now - v) >= _call_ids_impl.purge_timeout:
                 o_keys.append(k)
         for k in o_keys:
@@ -73,7 +73,7 @@ class _call_ids_impl (dict):
             del self[k]
         if debug:
             logger.debug("AFTER PURGE")
-            for (k, v) in self.iteritems():
+            for (k, v) in self.items():
                 logger.debug("%s -> %s" %
                              (k, time.strftime("%H:%M:%S", time.localtime(v))))
 
index 013768c..4024d2b 100644 (file)
@@ -1,4 +1,4 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python3
 import sys
 import os
 import time
index 513eb81..8ef4d8e 100644 (file)
@@ -28,7 +28,7 @@ except:
                 args = tuple()
             else:
                 args = self.default_factory,
-            return type(self), args, None, None, self.items()
+            return type(self), args, None, None, list(self.items())
 
         def copy(self):
             return self.__copy__()
@@ -39,7 +39,7 @@ except:
         def __deepcopy__(self, memo):
             import copy
             return type(self)(self.default_factory,
-                              copy.deepcopy(self.items()))
+                              copy.deepcopy(list(self.items())))
 
         def __repr__(self):
             return 'defaultdict(%s, %s)' % (self.default_factory,
index 8ddfcc1..6e6d3c3 100644 (file)
@@ -26,8 +26,8 @@ class Enum(set):
 
     def __init__(self, *args, **kwds):
         set.__init__(self)
-        enums = dict(zip(args, [object() for i in range(len(args))]), **kwds)
-        for (key, value) in enums.items():
+        enums = dict(list(zip(args, [object() for i in range(len(args))])), **kwds)
+        for (key, value) in list(enums.items()):
             setattr(self, key, value)
             self.add(eval('self.%s' % key))
 
index 44c368a..e99d55a 100644 (file)
@@ -143,7 +143,7 @@ class Method:
 
             # Indent struct fields and mixed types
             if isinstance(param, dict):
-                for name, subparam in param.iteritems():
+                for name, subparam in param.items():
                     text += param_text(name, subparam, indent + step, step)
             elif isinstance(param, Mixed):
                 for subparam in param:
@@ -176,9 +176,9 @@ class Method:
         """
 
         # Inspect call. Remove self from the argument list.
-        max_args = self.call.func_code.co_varnames[
-            1:self.call.func_code.co_argcount]
-        defaults = self.call.func_defaults
+        max_args = self.call.__code__.co_varnames[
+            1:self.call.__code__.co_argcount]
+        defaults = self.call.__defaults__
         if defaults is None:
             defaults = ()
 
@@ -288,14 +288,14 @@ class Method:
         # If a struct with particular (or required) types of items is
         # expected.
         elif isinstance(expected, dict):
-            for key in value.keys():
+            for key in list(value.keys()):
                 if key in expected:
                     self.type_check(name + "['%s']" %
                                     key, value[key], expected[key], args)
-            for key, subparam in expected.iteritems():
+            for key, subparam in expected.items():
                 if isinstance(subparam, Parameter) and \
                    subparam.optional is not None and \
-                   not subparam.optional and key not in value.keys():
+                   not subparam.optional and key not in list(value.keys()):
                     raise SfaInvalidArgument("'%s' not specified" % key, name)
 
         # if auth is not None:
index 2f5b5f0..62b9a92 100755 (executable)
@@ -1,4 +1,4 @@
-from __future__ import print_function
+
 
 
 class prefixNode:
index c5a2da6..d03e962 100644 (file)
@@ -11,7 +11,7 @@ def printable(record_s):
     if isinstance(record_s, list):
         return "[" + "\n".join([printable(r) for r in record_s]) + "]"
     if isinstance(record_s, dict):
-        return "{" + " , ".join(["%s:%s" % (k, beginning(v)) for k, v in record_s.iteritems()]) + "}"
+        return "{" + " , ".join(["%s:%s" % (k, beginning(v)) for k, v in record_s.items()]) + "}"
     if isinstance(record_s, str):
         return record_s
     return "unprintable [[%s]]" % record_s
index 7cd55cd..cb2e1e2 100644 (file)
@@ -2,27 +2,9 @@
 import sys
 PY3 = sys.version_info[0] == 3
 
-try:
-    StringType = basestring
-except:
-    StringType = str
+StringType = str
+from io import StringIO
 
-try:
-    from StringIO import StringIO
-except:
-    from io import StringIO
-
-try:
-    import xmlrpclib as xmlrpc_client
-except:
-    from xmlrpc import client as xmlrpc_client
-
-try:
-    import httplib as http_client
-except:
-    from http import client as http_client
-
-try:
-    import ConfigParser
-except:
-    import configparser as ConfigParser
+import xmlrpc.client as xmlrpc_client
+import http.client as http_client
+import configparser as ConfigParser
index 0789353..fd1cabf 100644 (file)
@@ -1,4 +1,4 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python3
 
 """
 A reroutable logger that can handle deep tracebacks
@@ -34,7 +34,7 @@ Implementation:
 
 # pylint: disable=c0111, c0103, w1201
 
-from __future__ import print_function
+
 
 import os
 import os.path
index 9752d32..6793ad5 100644 (file)
@@ -20,7 +20,7 @@
 # OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS
 # IN THE WORK.
 #----------------------------------------------------------------------
-from __future__ import print_function
+
 
 import time
 import datetime
@@ -80,7 +80,7 @@ For safety this can also handle inputs that are either timestamps, or datetimes
         if t.utcoffset() is not None:
             t = t.utcoffset() + t.replace(tzinfo=None)
         return t
-    elif isinstance(input, (int, float, long)):
+    elif isinstance(input, (int, float)):
         return datetime.datetime.fromtimestamp(input)
     else:
         logger.error("Unexpected type in utcparse [%s]" % type(input))
index 93d977f..d9e23d5 100755 (executable)
@@ -1,4 +1,4 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python3
 from lxml import etree
 from sfa.util.faults import InvalidXML
 from sfa.rspecs.elements.element import Element
@@ -29,7 +29,7 @@ class XpathFilter:
         xpath = ""
         if filter:
             filter_list = []
-            for (key, value) in filter.items():
+            for (key, value) in list(filter.items()):
                 if key == 'text':
                     key = 'text()'
                 else:
@@ -116,11 +116,11 @@ class XmlElement:
         if fields is None:
             fields = []
         if not fields and hasattr(instance, 'keys'):
-            fields = instance.keys()
+            fields = list(instance.keys())
         elem = self.add_element(name)
         for field in fields:
             if field in instance and instance[field]:
-                elem.set(field, unicode(instance[field]))
+                elem.set(field, str(instance[field]))
         return elem
 
     def remove_elements(self, name):
@@ -210,7 +210,7 @@ class XML:
 
         self.root = XmlElement(root, self.namespaces)
         # set schema
-        for key in self.root.attrib.keys():
+        for key in list(self.root.attrib.keys()):
             if key.endswith('schemaLocation'):
                 # schemaLocation should be at the end of the list.
                 # Use list comprehension to filter out empty strings
@@ -231,7 +231,7 @@ class XML:
             element.text = text
 
         # handle repeating fields
-        for (key, value) in d.items():
+        for (key, value) in list(d.items()):
             if isinstance(value, list):
                 value = d.pop(key)
                 for val in value:
@@ -243,7 +243,7 @@ class XML:
                             element, key).text = val
 
             elif isinstance(value, int):
-                d[key] = unicode(d[key])
+                d[key] = str(d[key])
             elif value is None:
                 d.pop(key)
 
@@ -251,7 +251,7 @@ class XML:
         # dcitionary.
         d = d.copy()
         # looks like iteritems won't stand side-effects
-        for k in d.keys():
+        for k in list(d.keys()):
             if not isinstance(d[k], StringType):
                 del d[k]
 
index 3646990..b1dff42 100644 (file)
@@ -15,7 +15,7 @@ class Delete(Command):
     def call(self, command_options, match_options, target_options):
 
         if (len(command_options.args)<2):
-            print "Please specify the chain and the rule number to delete, e.g. sfatables -D INCOMING 1."
+            print("Please specify the chain and the rule number to delete, e.g. sfatables -D INCOMING 1.")
             return
 
         chain = command_options.args[0]
index 852985e..63e3bea 100644 (file)
@@ -47,7 +47,7 @@ class Insert(Command):
 
     def call(self, command_options, match_options, target_options):
         if (len(command_options.args)<2):
-            print "Please specify the chain and the rule number to insert, e.g. sfatables -I INCOMING 1 -- ...."
+            print("Please specify the chain and the rule number to insert, e.g. sfatables -I INCOMING 1 -- ....")
             return
 
         chain = command_options.args[0]
index cea40bb..20576ba 100644 (file)
@@ -38,8 +38,8 @@ class List(Command):
             names = [n.content for n in name_nodes]
             values = [v.content for v in value_nodes]
 
-            name_values = zip(names,values)
-            name_value_pairs = map(lambda (n,v):n+'='+v, name_values)
+            name_values = list(zip(names,values))
+            name_value_pairs = [n_v[0]+'='+n_v[1] for n_v in name_values]
 
             argument_str = ",".join(name_value_pairs)
 
@@ -58,13 +58,13 @@ class List(Command):
                     (magic,number,type) = file.split('-')
                     rule_numbers[int(number)]=1
 
-        rule_list = rule_numbers.keys()
+        rule_list = list(rule_numbers.keys())
         rule_list.sort()
         return rule_list
 
     def call(self, command_options, match_options, target_options):
         if (len(command_options.args) < 1):
-            print "Please specify the name of the chain you would like to list, e.g. sfatables -L INCOMING."
+            print("Please specify the name of the chain you would like to list, e.g. sfatables -L INCOMING.")
             return
 
         chain = command_options.args[0]
index 65b7598..3860e3c 100644 (file)
@@ -59,7 +59,7 @@ class Command:
 
             # Indent struct fields and mixed types
             if isinstance(param, dict):
-                for name, subparam in param.iteritems():
+                for name, subparam in param.items():
                     text += param_text(name, subparam, indent + step, step)
             elif isinstance(param, Mixed):
                 for subparam in param:
@@ -92,8 +92,8 @@ class Command:
         """
         
         # Inspect call. Remove self from the argument list.
-        max_args = self.call.func_code.co_varnames[1:self.call.func_code.co_argcount]
-        defaults = self.call.func_defaults
+        max_args = self.call.__code__.co_varnames[1:self.call.__code__.co_argcount]
+        defaults = self.call.__defaults__
         if defaults is None:
             defaults = ()
 
@@ -199,13 +199,13 @@ class Command:
         # If a struct with particular (or required) types of items is
         # expected.
         elif isinstance(expected, dict):
-            for key in value.keys():
+            for key in list(value.keys()):
                 if key in expected:
                     self.type_check(name + "['%s']" % key, value[key], expected[key], args)
-            for key, subparam in expected.iteritems():
+            for key, subparam in expected.items():
                 if isinstance(subparam, Parameter) and \
                    subparam.optional is not None and \
-                   not subparam.optional and key not in value.keys():
+                   not subparam.optional and key not in list(value.keys()):
                     raise SfaInvalidArgument("'%s' not specified" % key, name)
 
         #if auth is not None:
index 87e74fb..77e1004 100644 (file)
@@ -1,4 +1,4 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python3
 
 class Pretty:
     rows = []
@@ -19,7 +19,7 @@ class Pretty:
         return
 
     def pprint (self):
-        print '\n'
+        print('\n')
 
         for rule in self.rows:
             cur_line = ""
@@ -33,6 +33,6 @@ class Pretty:
                     cur_line = cur_line + padding
                 num = num + 1
 
-            print cur_line
+            print(cur_line)
 
 
index d7eb6d4..f773b0d 100644 (file)
@@ -1,4 +1,4 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python3
 
 import sys
 import os
@@ -44,7 +44,7 @@ class SFATablesRules:
 
     def create_xml_node(self, name, context_dict):
         node = libxml2.newNode(name)
-        for k in context_dict.keys():
+        for k in list(context_dict.keys()):
             if (type(context_dict[k])==dict):
                 childNode = self.create_xml_node(k, context_dict[k])
                 node.addChild(childNode)
@@ -87,22 +87,22 @@ class SFATablesRules:
 
     def print_rules(self):
         for rule in self.sorted_rule_list:
-            print rule.processors
+            print(rule.processors)
 
 def main():
     incoming = SFATablesRules('INCOMING')
     incoming.set_context({'sfa':{'user':{'hrn':'plc.princeton.sapanb'}}})
 
     outgoing = SFATablesRules('OUTGOING')
-    print "%d rules loaded for INCOMING chain"%len(incoming.sorted_rule_list)
+    print("%d rules loaded for INCOMING chain"%len(incoming.sorted_rule_list))
     incoming.print_rules()
 
-    print "%d rules loaded for OUTGOING chain"%len(outgoing.sorted_rule_list)
+    print("%d rules loaded for OUTGOING chain"%len(outgoing.sorted_rule_list))
     outgoing.print_rules()
 
     rspec = open(sys.argv[1]).read()
     newrspec = incoming.apply(rspec)
-    print newrspec
+    print(newrspec)
     return
 
 if __name__=="__main__":
index f90e0fb..dcc0419 100644 (file)
@@ -37,7 +37,7 @@ class Xmlextension:
         context = p.xpathEval('//attributes/attribute[@terminal="yes"]')
         self.terminal = (context != [])
 
-        self.arguments = map(lambda (name,help,target):{'name':name.content,'help':help.content,'target':target.content}, zip(name,help,target))
+        self.arguments = [{'name':name_help_target[0].content,'help':name_help_target[1].content,'target':name_help_target[2].content} for name_help_target in zip(name,help,target)]
         
         p.xpathFreeContext()
         self.xmldoc.freeDoc()
index ff3b3ef..b749147 100644 (file)
@@ -3,7 +3,7 @@ import sys,os
 import libxml2
 # allow to run sfa2wsdl if this is missing (for mac)
 try:import libxslt
-except: print >>sys.stderr, "WARNING, could not import libxslt"
+except: print("WARNING, could not import libxslt", file=sys.stderr)
 
 from sfatables.globals import sfatables_config
 
index b276984..d78352b 100644 (file)
@@ -5,7 +5,7 @@ from sfa.trust.credential import *
 
 cred = Credential(filename = 'tmack.pl.sa.cred')
 slicehrn = 'planetlab.us.pl.tmack'
-print cred.get_privileges().save_to_string()
+print(cred.get_privileges().save_to_string())
 
 r = GeniClient('https://128.112.139.120:12345', 'tmack.pkey', 'tmack.cert') 
 a = GeniClient('https://128.112.139.120:12346', 'tmack.pkey', 'tmack.cert')
@@ -13,18 +13,18 @@ a = GeniClient('https://128.112.139.120:12346', 'tmack.pkey', 'tmack.cert')
 #pprint(r.list(cred, 'planetlab.us.princeton'))
 pprint(a.get_policy(cred))
 
-print "components at this aggregate"
+print("components at this aggregate")
 components = a.list_components()
 pprint(components)
 
-print "resources being used by %(slicehrn)s" % locals()
+print("resources being used by %(slicehrn)s" % locals())
 tmack_components = a.list_resources(cred, slicehrn)
 pprint(tmack_components)
 
 #print "removing %(slicehrn)s from all nodes" % locals()
 #a.DeleteSliver(cred, slicehrn)
 
-print "adding %(slicehrn)s back to its original nodes" % locals()
+print("adding %(slicehrn)s back to its original nodes" % locals())
 a.list_resources(cred, slicehrn)
 a.CreateSliver(cred, slicehrn, components)
 a.list_resources(cred, slicehrn)
index 7664c8a..0248954 100755 (executable)
@@ -1,4 +1,4 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python3
 from testXrn import *
 #from testNamespace import *
 # xxx broken-test
index b2e8133..1d00d27 100755 (executable)
@@ -112,7 +112,7 @@ class TestCert(unittest.TestCase):
       cert.sign()
 
       result = cert.verify(issuerKey)
-      self.assert_(result)
+      self.assertTrue(result)
 
       # create another key
       issuerKey2 = Keypair(create=True)
@@ -120,14 +120,14 @@ class TestCert(unittest.TestCase):
 
       # and make sure it doesn't verify
       result = cert.verify(issuerKey2)
-      self.assert_(not result)
+      self.assertTrue(not result)
 
       # load the cert from a string, and verify again
       cert2 = Certificate(string = cert.save_to_string())
       result = cert2.verify(issuerKey)
-      self.assert_(result)
+      self.assertTrue(result)
       result = cert2.verify(issuerKey2)
-      self.assert_(not result)
+      self.assertTrue(not result)
 
    def test_is_signed_by(self):
       cert1 = Certificate(subject="one")
@@ -150,9 +150,9 @@ class TestCert(unittest.TestCase):
       cert2.set_issuer(key1, cert=cert1)
 
       # cert2 is signed by cert1
-      self.assert_(cert2.is_signed_by_cert(cert1))
+      self.assertTrue(cert2.is_signed_by_cert(cert1))
       # cert1 is not signed by cert2
-      self.assert_(not cert1.is_signed_by_cert(cert2))
+      self.assertTrue(not cert1.is_signed_by_cert(cert2))
 
    def test_parents(self):
       cert_root = Certificate(subject="root")
@@ -181,9 +181,9 @@ class TestCert(unittest.TestCase):
       cert3.set_parent(cert2)
       cert3.sign()
 
-      self.assert_(cert1.verify(key_root))
-      self.assert_(cert2.is_signed_by_cert(cert1))
-      self.assert_(cert3.is_signed_by_cert(cert2))
+      self.assertTrue(cert1.verify(key_root))
+      self.assertTrue(cert2.is_signed_by_cert(cert1))
+      self.assertTrue(cert3.is_signed_by_cert(cert2))
 
       cert3.verify_chain([cert_root])
 
index 723c6db..379d850 100755 (executable)
@@ -26,25 +26,25 @@ class TestHierarchy(unittest.TestCase):
 
         h.create_auth(name, create_parents=True)
         auth_info = h.get_auth_info(name)
-        self.assert_(auth_info)
+        self.assertTrue(auth_info)
 
         gid = auth_info.get_gid_object()
-        self.assert_(gid)
+        self.assertTrue(gid)
         self.assertEqual(gid.get_subject(), name)
 
         pubkey = auth_info.get_pkey_object()
-        self.assert_(gid)
+        self.assertTrue(gid)
 
         # try to get it again, make sure it's still there
         auth_info2 = h.get_auth_info(name)
-        self.assert_(auth_info2)
+        self.assertTrue(auth_info2)
 
         gid = auth_info2.get_gid_object()
-        self.assert_(gid)
+        self.assertTrue(gid)
         self.assertEqual(gid.get_subject(), name)
 
         pubkey = auth_info2.get_pkey_object()
-        self.assert_(gid)
+        self.assertTrue(gid)
 
 
 if __name__ == "__main__":
index 1ab8048..520d94a 100755 (executable)
@@ -1,4 +1,4 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python3
 import sys
 import os
 import random
@@ -30,7 +30,7 @@ class Client:
     def __init__(self, options):
         try: self.config = config = Config(options.config_file)
         except:
-            print "failed to read config_file %s" % options.config_file
+            print("failed to read config_file %s" % options.config_file)
             sys.exit(1)
         key_path = os.path.dirname(options.config_file)
         user_name = self.config.SFI_USER.split('.')[-1:][0]
index 8d55e86..c9254ec 100755 (executable)
@@ -1,4 +1,4 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python3
 import sys
 sys.path.append('..')
 
@@ -30,14 +30,14 @@ class TestKeypair(unittest.TestCase):
       k.create()
 
       m2 = k.get_m2_pubkey()
-      self.assert_(m2 != None)
+      self.assertTrue(m2 != None)
 
    def test_get_openssl_pkey(self):
       k = Keypair()
       k.create()
 
       pk = k.get_openssl_pkey()
-      self.assert_(pk != None)
+      self.assertTrue(pk != None)
 
    def test_sign_verify(self):
       k = Keypair()
@@ -46,7 +46,7 @@ class TestKeypair(unittest.TestCase):
       data = "this is a test"
       sig = k.sign_string(data)
 
-      print k.verify_string(data, sig)
+      print(k.verify_string(data, sig))
 
 if __name__ == "__main__":
     unittest.main()
index a65c9dd..f5cb9ad 100755 (executable)
@@ -11,24 +11,24 @@ class TestRight(unittest.TestCase):
 
    def testRightCanPerform(self):
       right = Right("embed")
-      self.assert_(right.can_perform("getticket"))
-      self.assert_(not right.can_perform("resolve"))
+      self.assertTrue(right.can_perform("getticket"))
+      self.assertTrue(not right.can_perform("resolve"))
 
    def testIsSuperset(self):
       pright = Right("sa")
       cright = Right("embed")
-      self.assert_(pright.is_superset(cright))
-      self.assert_(not cright.is_superset(pright))
+      self.assertTrue(pright.is_superset(cright))
+      self.assertTrue(not cright.is_superset(pright))
 
       pright = Right("embed")
       cright = Right("embed")
-      self.assert_(pright.is_superset(cright))
-      self.assert_(cright.is_superset(pright))
+      self.assertTrue(pright.is_superset(cright))
+      self.assertTrue(cright.is_superset(pright))
 
       pright = Right("control")
       cright = Right("embed")
-      self.assert_(not pright.is_superset(cright))
-      self.assert_(not cright.is_superset(pright))
+      self.assertTrue(not pright.is_superset(cright))
+      self.assertTrue(not cright.is_superset(pright))
 
 class TestRights(unittest.TestCase):
     def setUp(self):
@@ -53,33 +53,33 @@ class TestRights(unittest.TestCase):
 
     def testCanPerform(self):
         rightList = Rights(string="embed")
-        self.assert_(rightList.can_perform("getticket"))
-        self.assert_(not rightList.can_perform("resolve"))
+        self.assertTrue(rightList.can_perform("getticket"))
+        self.assertTrue(not rightList.can_perform("resolve"))
 
         rightList = Rights(string="embed,resolve")
-        self.assert_(rightList.can_perform("getticket"))
-        self.assert_(rightList.can_perform("resolve"))
+        self.assertTrue(rightList.can_perform("getticket"))
+        self.assertTrue(rightList.can_perform("resolve"))
 
     def testIsSuperset(self):
         pRights = Rights(string="sa")
         cRights = Rights(string="embed")
-        self.assert_(pRights.is_superset(cRights))
-        self.assert_(not cRights.is_superset(pRights))
+        self.assertTrue(pRights.is_superset(cRights))
+        self.assertTrue(not cRights.is_superset(pRights))
 
         pRights = Rights(string="embed")
         cRights = Rights(string="embed")
-        self.assert_(pRights.is_superset(cRights))
-        self.assert_(cRights.is_superset(pRights))
+        self.assertTrue(pRights.is_superset(cRights))
+        self.assertTrue(cRights.is_superset(pRights))
 
         pRights = Rights(string="control")
         cRights = Rights(string="embed")
-        self.assert_(not pRights.is_superset(cRights))
-        self.assert_(not cRights.is_superset(pRights))
+        self.assertTrue(not pRights.is_superset(cRights))
+        self.assertTrue(not cRights.is_superset(pRights))
 
         pRights = Rights(string="control,sa")
         cRights = Rights(string="embed")
-        self.assert_(pRights.is_superset(cRights))
-        self.assert_(not cRights.is_superset(pRights))
+        self.assertTrue(pRights.is_superset(cRights))
+        self.assertTrue(not cRights.is_superset(pRights))
 
 
 if __name__ == "__main__":
index 68506b2..6aae326 100755 (executable)
@@ -1,4 +1,4 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python3
 import sys
 import unittest
 
@@ -12,13 +12,13 @@ verbose=False
 class TestXrn(unittest.TestCase):
 
     def __hrn(self,h,t,exp_urn):
-        if verbose: print 'testing (',h,t,') expecting',exp_urn
+        if verbose: print('testing (',h,t,') expecting',exp_urn)
         xrn=Xrn(h,type=t)
-        if verbose: print xrn.dump_string()
+        if verbose: print(xrn.dump_string())
         urn=xrn.get_urn()
         (h1,t1) = Xrn(urn).get_hrn_type()
         if h1!=h or t1!=t or urn!=exp_urn:
-            print "hrn->urn->hrn : MISMATCH with in=(%s,%s) -- out=(%s,%s) -- urn=%s"%(h,t,h1,t1,urn)
+            print("hrn->urn->hrn : MISMATCH with in=(%s,%s) -- out=(%s,%s) -- urn=%s"%(h,t,h1,t1,urn))
         self.assertEqual(h1,h)
         self.assertEqual(t1,t)
         self.assertEqual(urn,exp_urn)
index c9c035b..3c9978c 100755 (executable)
@@ -1,4 +1,4 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python3
 # Copyright 2004 Toby Dickenson
 #
 # Permission is hereby granted, free of charge, to any person obtaining
@@ -46,8 +46,8 @@ class pydepgraphdot:
         p, t = self.get_data()
 
         # normalise our input data
-        for k, d in p.items():
-            for v in d.keys():
+        for k, d in list(p.items()):
+            for v in list(d.keys()):
                 if v not in p:
                     p[v] = {}
 
@@ -58,12 +58,12 @@ class pydepgraphdot:
         #f.write('ordering = out;\n')
         f.write('ranksep=1.0;\n')
         f.write('node [style=filled,fontname=Helvetica,fontsize=10];\n')
-        allkd = p.items()
+        allkd = list(p.items())
         allkd.sort()
         for k, d in allkd:
             tk = t.get(k)
             if self.use(k, tk):
-                allv = d.keys()
+                allv = list(d.keys())
                 allv.sort()
                 for v in allv:
                     tv = t.get(v)
index bb3f40f..40ef598 100755 (executable)
@@ -1,4 +1,4 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python3
 # Copyright 2004,2009 Toby Dickenson
 #
 # Permission is hereby granted, free of charge, to any person obtaining
@@ -49,7 +49,7 @@ class mymf(modulefinder.ModuleFinder):
             if fqname.startswith(start):
                 keep = True
         if not keep:
-            print >> sys.stderr, "Trimmed fqname", fqname
+            print("Trimmed fqname", fqname, file=sys.stderr)
             return
         r = modulefinder.ModuleFinder.import_module(
             self, partnam, fqname, parent)
@@ -58,7 +58,8 @@ class mymf(modulefinder.ModuleFinder):
                 r.__name__] = 1
         return r
 
-    def load_module(self, fqname, fp, pathname, (suffix, mode, type)):
+    def load_module(self, fqname, fp, pathname, xxx_todo_changeme):
+        (suffix, mode, type) = xxx_todo_changeme
         r = modulefinder.ModuleFinder.load_module(
             self, fqname, fp, pathname, (suffix, mode, type))
         if r is not None:
index 58fa709..f6fd2ea 100755 (executable)
@@ -1,4 +1,4 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python3
 #
 # Sapan Bhatia <sapanb@cs.princeton.edu>
 #
@@ -259,7 +259,7 @@ class WSDLGen:
 
 
     def add_wsdl_services(self):
-        for service in self.services.keys():
+        for service in list(self.services.keys()):
             if (getattr(self.interface_options,service)):
                 service_el = self.wsdl.lastChild.appendChild(self.wsdl.createElement("service"))
                 service_el.setAttribute("name", service)
@@ -325,7 +325,7 @@ class WSDLGen:
 
     def pretty_print(self):
         if (self.wsdl):
-             print xml.dom.minidom.Document.toprettyxml(self.wsdl)
+             print(xml.dom.minidom.Document.toprettyxml(self.wsdl))
         else:
              raise Exception("Empty WSDL")