From: parmentelat Date: Fri, 7 Dec 2018 19:32:28 +0000 (+0100) Subject: blind 2to3 X-Git-Tag: plcapi-7.0-0~41 X-Git-Url: http://git.onelab.eu/?a=commitdiff_plain;h=3b44c0228c26dc43d985185afc225caa5f48c1fb;p=plcapi.git blind 2to3 --- diff --git a/PLC/API.py b/PLC/API.py index b213c380..5b514e0f 100644 --- a/PLC/API.py +++ b/PLC/API.py @@ -7,13 +7,13 @@ # Copyright (C) 2004-2006 The Trustees of Princeton University # -from __future__ import print_function + import os import string import json -import xmlrpclib +import xmlrpc.client # See "2.2 Characters" in the XML specification: # @@ -21,7 +21,7 @@ import xmlrpclib # avoiding # [#x7F-#x84], [#x86-#x9F], [#xFDD0-#xFDDF] -invalid_codepoints = range(0x0, 0x8) + [0xB, 0xC] + range(0xE, 0x1F) +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 = \ @@ -31,7 +31,7 @@ str_xml_escape_table = \ # 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} + {invalid: "?" for invalid in invalid_codepoints} def xmlrpclib_escape(s, replace=string.replace): @@ -58,7 +58,7 @@ def test_xmlrpclib_escape(): # full ASCII "".join((chr(x) for x in range(128))), # likewise but as a unicode string up to 256 - u"".join((unichr(x) for x in range(256))), + "".join((chr(x) for x in range(256))), ] for input in inputs: print("==================== xmlrpclib_escape INPUT") @@ -80,7 +80,7 @@ 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: @@ -88,7 +88,7 @@ def xmlrpclib_dump(self, value, write): f = self.dispatch[type(value)] except KeyError: # 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 @@ -98,7 +98,7 @@ def xmlrpclib_dump(self, value, write): # You can't hide from me! -xmlrpclib.Marshaller._Marshaller__dump = xmlrpclib_dump +xmlrpc.client.Marshaller._Marshaller__dump = xmlrpclib_dump # SOAP support is optional try: @@ -141,7 +141,7 @@ class PLCAPI: for method in getattr(import_deep(fullpath), "methods"): other_methods_map[method] = fullpath - all_methods = native_methods + other_methods_map.keys() + all_methods = native_methods + list(other_methods_map.keys()) def __init__(self, config="/etc/planetlab/plc_config", encoding="utf-8"): @@ -234,7 +234,7 @@ class PLCAPI: # Parse request into method name and arguments try: interface = xmlrpclib - (args, method) = xmlrpclib.loads(data) + (args, method) = xmlrpc.client.loads(data) methodresponse = True except Exception as exc: if SOAPpy is not None: @@ -264,7 +264,7 @@ class PLCAPI: if interface == xmlrpclib: if not isinstance(result, PLCFault): result = (result,) - data = xmlrpclib.dumps(result, methodresponse=True, + data = xmlrpc.client.dumps(result, methodresponse=True, encoding=self.encoding, allow_none=1) elif interface == SOAPpy: data = buildSOAP( diff --git a/PLC/Accessor.py b/PLC/Accessor.py index e32add4b..4530bad7 100644 --- a/PLC/Accessor.py +++ b/PLC/Accessor.py @@ -34,7 +34,7 @@ class Accessor(object): self.hash_name_to_role = {role['name']: role for role in Roles(api)} def has_cache(self, tagname): - return self.cache.has_key(tagname) + return tagname in self.cache def get_cache(self, tagname): return self.cache[tagname] @@ -106,7 +106,7 @@ class Accessor(object): # it's not easy to have define_accessors do this because at # load-time as we do not have an instance of API yet def run_all_tag_locators(self): - for (name, tag_locator) in Accessor.tag_locators.items(): + for (name, tag_locator) in list(Accessor.tag_locators.items()): tag_locator(self, enforce=True) #################### diff --git a/PLC/Accessors/Factory.py b/PLC/Accessors/Factory.py index fec0d63e..ce39769f 100644 --- a/PLC/Accessors/Factory.py +++ b/PLC/Accessors/Factory.py @@ -87,9 +87,9 @@ def define_accessors_ (module, objclass, methodsuffix, tagname, if objclass not in taggable_classes: try: - raise PLCInvalidArgument,"PLC.Accessors.Factory: unknown class %s"%objclass.__name__ + raise PLCInvalidArgument("PLC.Accessors.Factory: unknown class %s"%objclass.__name__) except: - raise PLCInvalidArgument,"PLC.Accessors.Factory: unknown class ??" + raise PLCInvalidArgument("PLC.Accessors.Factory: unknown class ??") # side-effect on, say, Node.tags, if required if expose_in_api: @@ -182,7 +182,7 @@ def define_accessors_ (module, objclass, methodsuffix, tagname, # objs = table_class(self.api, filter,[primary_key,secondary_key]) objs = table_class(self.api, filter) if not objs: - raise PLCInvalidArgument, "Cannot set tag on %s %r"%(objclass.__name__,id_or_name) + raise PLCInvalidArgument("Cannot set tag on %s %r"%(objclass.__name__,id_or_name)) # the object being tagged obj=objs[0] primary_id = obj[primary_key] @@ -194,7 +194,7 @@ def define_accessors_ (module, objclass, methodsuffix, tagname, # check authorization if not hasattr(objclass,'caller_may_write_tag'): - raise PLCAuthenticationFailure, "class %s misses method caller_may_write_tag"%objclass.__name__ + raise PLCAuthenticationFailure("class %s misses method caller_may_write_tag"%objclass.__name__) obj.caller_may_write_tag (self.api,self.caller,tag_type) # locate the join object (e.g. NodeTag or similar) diff --git a/PLC/AddressTypes.py b/PLC/AddressTypes.py index e4ad4de7..acc00258 100644 --- a/PLC/AddressTypes.py +++ b/PLC/AddressTypes.py @@ -29,13 +29,13 @@ class AddressType(Row): def validate_name(self, name): # Make sure name is not blank if not len(name): - raise PLCInvalidArgument, "Address type must be specified" + raise PLCInvalidArgument("Address type must be specified") # Make sure address type does not already exist conflicts = AddressTypes(self.api, [name]) for address_type_id in conflicts: if 'address_type_id' not in self or self['address_type_id'] != address_type_id: - raise PLCInvalidArgument, "Address type name already in use" + raise PLCInvalidArgument("Address type name already in use") return name @@ -53,20 +53,20 @@ class AddressTypes(Table): if address_type_filter is not None: if isinstance(address_type_filter, (list, tuple, set)): # Separate the list into integers and strings - ints = filter(lambda x: isinstance(x, (int, long)), address_type_filter) - strs = filter(lambda x: isinstance(x, StringTypes), address_type_filter) + ints = [x for x in address_type_filter if isinstance(x, int)] + strs = [x for x in address_type_filter if isinstance(x, StringTypes)] address_type_filter = Filter(AddressType.fields, {'address_type_id': ints, 'name': strs}) sql += " AND (%s) %s" % address_type_filter.sql(api, "OR") elif isinstance(address_type_filter, dict): address_type_filter = Filter(AddressType.fields, address_type_filter) sql += " AND (%s) %s" % address_type_filter.sql(api, "AND") - elif isinstance(address_type_filter, (int, long)): + elif isinstance(address_type_filter, int): address_type_filter = Filter(AddressType.fields, {'address_type_id': address_type_filter}) sql += " AND (%s) %s" % address_type_filter.sql(api, "AND") elif isinstance(address_type_filter, StringTypes): address_type_filter = Filter(AddressType.fields, {'name': address_type_filter}) sql += " AND (%s) %s" % address_type_filter.sql(api, "AND") else: - raise PLCInvalidArgument, "Wrong address type filter %r"%address_type_filter + raise PLCInvalidArgument("Wrong address type filter %r"%address_type_filter) self.selectall(sql) diff --git a/PLC/Addresses.py b/PLC/Addresses.py index 6d6aceeb..6c095cce 100644 --- a/PLC/Addresses.py +++ b/PLC/Addresses.py @@ -90,7 +90,7 @@ class Addresses(Table): ", ".join(self.columns) if address_filter is not None: - if isinstance(address_filter, (list, tuple, set, int, long)): + if isinstance(address_filter, (list, tuple, set, int)): address_filter = Filter(Address.fields, {'address_id': address_filter}) elif isinstance(address_filter, dict): address_filter = Filter(Address.fields, address_filter) diff --git a/PLC/Auth.py b/PLC/Auth.py index 3be444bb..f18c7315 100644 --- a/PLC/Auth.py +++ b/PLC/Auth.py @@ -46,7 +46,7 @@ class Auth(Parameter): if auth['AuthMethod'] in auth_methods: expected = auth_methods[auth['AuthMethod']]() else: - sm = "'" + "', '".join(auth_methods.keys()) + "'" + sm = "'" + "', '".join(list(auth_methods.keys())) + "'" raise PLCInvalidArgument("must be " + sm, "AuthMethod") # Re-check using the specified authentication method @@ -69,36 +69,36 @@ class GPGAuth(Auth): peers = Peers(method.api, [auth['name']]) if peers: if 'peer' not in method.roles: - raise PLCAuthenticationFailure, "GPGAuth: Not allowed to call method, missing 'peer' role" + raise PLCAuthenticationFailure("GPGAuth: Not allowed to call method, missing 'peer' role") method.caller = peer = peers[0] gpg_keys = [ peer['key'] ] else: persons = Persons(method.api, {'email': auth['name'], 'enabled': True, 'peer_id': None}) if not persons: - raise PLCAuthenticationFailure, "GPGAuth: No such user '%s'" % auth['name'] + raise PLCAuthenticationFailure("GPGAuth: No such user '%s'" % auth['name']) method.caller = person = persons[0] if not set(person['roles']).intersection(method.roles): - raise PLCAuthenticationFailure, "GPGAuth: Not allowed to call method, missing role" + raise PLCAuthenticationFailure("GPGAuth: Not allowed to call method, missing role") keys = Keys(method.api, {'key_id': person['key_ids'], 'key_type': "gpg", 'peer_id': None}) gpg_keys = [ key['key'] for key in keys ] if not gpg_keys: - raise PLCAuthenticationFailure, "GPGAuth: No GPG key on record for peer or user '%s'"%auth['name'] + raise PLCAuthenticationFailure("GPGAuth: No GPG key on record for peer or user '%s'"%auth['name']) for gpg_key in gpg_keys: try: from PLC.GPG import gpg_verify gpg_verify(args, gpg_key, auth['signature'], method.name) return - except PLCAuthenticationFailure, fault: + except PLCAuthenticationFailure as fault: pass raise fault - except PLCAuthenticationFailure, fault: + except PLCAuthenticationFailure as fault: # XXX Send e-mail raise fault @@ -118,46 +118,46 @@ class SessionAuth(Auth): def check(self, method, auth, *args): # Method.type_check() should have checked that all of the # mandatory fields were present. - assert auth.has_key('session') + assert 'session' in auth # Get session record sessions = Sessions(method.api, [auth['session']], expires = None) if not sessions: - raise PLCAuthenticationFailure, "SessionAuth: No such session" + raise PLCAuthenticationFailure("SessionAuth: No such session") session = sessions[0] try: if session['node_id'] is not None: nodes = Nodes(method.api, {'node_id': session['node_id'], 'peer_id': None}) if not nodes: - raise PLCAuthenticationFailure, "SessionAuth: No such node" + raise PLCAuthenticationFailure("SessionAuth: No such node") node = nodes[0] if 'node' not in method.roles: # using PermissionDenied rather than AuthenticationFailure here because # if that fails we don't want to delete the session.. - raise PLCPermissionDenied, "SessionAuth: Not allowed to call method %s, missing 'node' role"%method.name + raise PLCPermissionDenied("SessionAuth: Not allowed to call method %s, missing 'node' role"%method.name) method.caller = node elif session['person_id'] is not None and session['expires'] > time.time(): persons = Persons(method.api, {'person_id': session['person_id'], 'enabled': True, 'peer_id': None}) if not persons: - raise PLCAuthenticationFailure, "SessionAuth: No such enabled account" + raise PLCAuthenticationFailure("SessionAuth: No such enabled account") person = persons[0] if not set(person['roles']).intersection(method.roles): method_message="method %s has roles [%s]"%(method.name,','.join(method.roles)) person_message="caller %s has roles [%s]"%(person['email'],','.join(person['roles'])) # not PLCAuthenticationFailure b/c that would end the session.. - raise PLCPermissionDenied, "SessionAuth: missing role, %s -- %s"%(method_message,person_message) + raise PLCPermissionDenied("SessionAuth: missing role, %s -- %s"%(method_message,person_message)) method.caller = person else: - raise PLCAuthenticationFailure, "SessionAuth: Invalid session" + raise PLCAuthenticationFailure("SessionAuth: Invalid session") - except PLCAuthenticationFailure, fault: + except PLCAuthenticationFailure as fault: session.delete() raise fault @@ -193,32 +193,32 @@ class BootAuth(Auth): # Yes, the comments in the old implementation are # misleading. Keys of dicts are not included in the # hash. - values += self.canonicalize(arg.values()) + values += self.canonicalize(list(arg.values())) else: # We use unicode() instead of str(). - values.append(unicode(arg)) + values.append(str(arg)) return values def check(self, method, auth, *args): # Method.type_check() should have checked that all of the # mandatory fields were present. - assert auth.has_key('node_id') + assert 'node_id' in auth if 'node' not in method.roles: - raise PLCAuthenticationFailure, "BootAuth: Not allowed to call method, missing 'node' role" + raise PLCAuthenticationFailure("BootAuth: Not allowed to call method, missing 'node' role") try: nodes = Nodes(method.api, {'node_id': auth['node_id'], 'peer_id': None}) if not nodes: - raise PLCAuthenticationFailure, "BootAuth: No such node" + raise PLCAuthenticationFailure("BootAuth: No such node") node = nodes[0] # Jan 2011 : removing support for old boot CDs if node['key']: key = node['key'] else: - raise PLCAuthenticationFailure, "BootAuth: No node key" + raise PLCAuthenticationFailure("BootAuth: No node key") # Yes, this is the "canonicalization" method used. args = self.canonicalize(args) @@ -231,11 +231,11 @@ class BootAuth(Auth): digest = hmac.new(str(key), msg.encode('utf-8'), sha).hexdigest() if digest != auth['value']: - raise PLCAuthenticationFailure, "BootAuth: Call could not be authenticated" + raise PLCAuthenticationFailure("BootAuth: Call could not be authenticated") method.caller = node - except PLCAuthenticationFailure, fault: + except PLCAuthenticationFailure as fault: if nodes: notify_owners(method, node, 'authfail', include_pis = True, include_techs = True, fault = fault) raise fault @@ -252,7 +252,7 @@ class AnonymousAuth(Auth): def check(self, method, auth, *args): if 'anonymous' not in method.roles: - raise PLCAuthenticationFailure, "AnonymousAuth: method cannot be called anonymously" + raise PLCAuthenticationFailure("AnonymousAuth: method cannot be called anonymously") method.caller = None @@ -271,12 +271,12 @@ class PasswordAuth(Auth): def check(self, method, auth, *args): # Method.type_check() should have checked that all of the # mandatory fields were present. - assert auth.has_key('Username') + assert 'Username' in auth # Get record (must be enabled) persons = Persons(method.api, {'email': auth['Username'].lower(), 'enabled': True, 'peer_id': None}) if len(persons) != 1: - raise PLCAuthenticationFailure, "PasswordAuth: No such account" + raise PLCAuthenticationFailure("PasswordAuth: No such account") person = persons[0] @@ -287,13 +287,13 @@ class PasswordAuth(Auth): # only be used on particular machines (those in a list). sources = method.api.config.PLC_API_MAINTENANCE_SOURCES.split() if method.source is not None and method.source[0] not in sources: - raise PLCAuthenticationFailure, "PasswordAuth: Not allowed to login to maintenance account" + raise PLCAuthenticationFailure("PasswordAuth: Not allowed to login to maintenance account") # Not sure why this is not stored in the DB password = method.api.config.PLC_API_MAINTENANCE_PASSWORD if auth['AuthString'] != password: - raise PLCAuthenticationFailure, "PasswordAuth: Maintenance account password verification failed" + raise PLCAuthenticationFailure("PasswordAuth: Maintenance account password verification failed") else: # Compare encrypted plaintext against encrypted password stored in the DB plaintext = auth['AuthString'].encode(method.api.encoding) @@ -302,12 +302,12 @@ class PasswordAuth(Auth): # Protect against blank passwords in the DB if password is None or password[:12] == "" or \ crypt.crypt(plaintext, password[:12]) != password: - raise PLCAuthenticationFailure, "PasswordAuth: Password verification failed" + raise PLCAuthenticationFailure("PasswordAuth: Password verification failed") if not set(person['roles']).intersection(method.roles): method_message="method %s has roles [%s]"%(method.name,','.join(method.roles)) person_message="caller %s has roles [%s]"%(person['email'],','.join(person['roles'])) - raise PLCAuthenticationFailure, "PasswordAuth: missing role, %s -- %s"%(method_message,person_message) + raise PLCAuthenticationFailure("PasswordAuth: missing role, %s -- %s"%(method_message,person_message)) method.caller = person @@ -322,12 +322,12 @@ auth_methods = {'session': SessionAuth, path = os.path.dirname(__file__) + "/Auth.d" try: extensions = os.listdir(path) -except OSError, e: +except OSError as e: extensions = [] for extension in extensions: if extension.startswith("."): continue if not extension.endswith(".py"): continue - execfile("%s/%s" % (path, extension)) + exec(compile(open("%s/%s" % (path, extension)).read(), "%s/%s" % (path, extension), 'exec')) del extensions diff --git a/PLC/AuthorizeHelpers.py b/PLC/AuthorizeHelpers.py index ec8daafa..1eedf258 100644 --- a/PLC/AuthorizeHelpers.py +++ b/PLC/AuthorizeHelpers.py @@ -21,7 +21,7 @@ class AuthorizeHelpers: elif isinstance(caller,Node): return 'node' in tag_type['roles'] else: - raise PLCInvalidArgument, "caller_may_access_tag_type - unexpected arg" + raise PLCInvalidArgument("caller_may_access_tag_type - unexpected arg") @staticmethod def person_may_access_person (api, caller_person, subject_person): @@ -104,14 +104,14 @@ def caller_may_write_node_tag (node, api, caller, tag_type): if 'roles' in caller and 'admin' in caller['roles']: pass elif not AuthorizeHelpers.caller_may_access_tag_type (api, caller, tag_type): - raise PLCPermissionDenied, "Role mismatch for writing tag %s"%(tag_type['tagname']) + raise PLCPermissionDenied("Role mismatch for writing tag %s"%(tag_type['tagname'])) elif AuthorizeHelpers.node_belongs_to_person (api, node, caller): pass elif AuthorizeHelpers.caller_is_node (api, caller, node): pass else: - raise PLCPermissionDenied, "Writing node tag: must belong in the same site as %s"%\ - (node['hostname']) + raise PLCPermissionDenied("Writing node tag: must belong in the same site as %s"%\ + (node['hostname'])) setattr(Node,'caller_may_write_tag',caller_may_write_node_tag) @@ -120,12 +120,12 @@ def caller_may_write_interface_tag (interface, api, caller, tag_type): if 'roles' in caller and 'admin' in caller['roles']: pass elif not AuthorizeHelpers.caller_may_access_tag_type (api, caller, tag_type): - raise PLCPermissionDenied, "Role mismatch for writing tag %s"%(tag_type['tagname']) + raise PLCPermissionDenied("Role mismatch for writing tag %s"%(tag_type['tagname'])) elif AuthorizeHelpers.interface_belongs_to_person (api, interface, caller): pass else: - raise PLCPermissionDenied, "Writing interface tag: must belong in the same site as %s"%\ - (interface['ip']) + raise PLCPermissionDenied("Writing interface tag: must belong in the same site as %s"%\ + (interface['ip'])) setattr(Interface,'caller_may_write_tag',caller_may_write_interface_tag) @@ -134,11 +134,11 @@ def caller_may_write_site_tag (site, api, caller, tag_type): if 'roles' in caller and 'admin' in caller['roles']: pass elif not AuthorizeHelpers.caller_may_access_tag_type (api, caller, tag_type): - raise PLCPermissionDenied, "Role mismatch for writing tag %s"%(tag_type['tagname']) + raise PLCPermissionDenied("Role mismatch for writing tag %s"%(tag_type['tagname'])) elif AuthorizeHelpers.person_in_site (api, caller, site): pass else: - raise PLCPermissionDenied, "Writing site tag: must be part of site"%site['login_base'] + raise PLCPermissionDenied("Writing site tag: must be part of site"%site['login_base']) setattr(Site,'caller_may_write_tag',caller_may_write_site_tag) @@ -150,7 +150,7 @@ def caller_may_write_person_tag (person, api, caller, tag_type): elif AuthorizeHelpers.person_may_access_person (api, caller, person): pass else: - raise PLCPermissionDenied, "Writing person tag: you can only change your own tags" + raise PLCPermissionDenied("Writing person tag: you can only change your own tags") setattr(Person,'caller_may_write_tag',caller_may_write_person_tag) @@ -182,12 +182,12 @@ def caller_may_write_slice_tag (slice, api, caller, tag_type, node_id_or_hostnam else: # only admins can handle slice tags on a nodegroup if nodegroup_id_or_name: - raise PLCPermissionDenied, "Cannot set slice tag %s on nodegroup - restricted to admins"%\ - (tag_type['tagname']) + raise PLCPermissionDenied("Cannot set slice tag %s on nodegroup - restricted to admins"%\ + (tag_type['tagname'])) # if a node is specified it is expected to be in the slice if node_id_or_hostname: if not AuthorizeHelpers.node_id_in_slice (api, node_id_or_hostname, slice): - raise PLCPermissionDenied, "%s, node must be in slice when setting sliver tag" + raise PLCPermissionDenied("%s, node must be in slice when setting sliver tag") # try all roles to find a match - tech are ignored b/c not in AddSliceTag.roles anyways for role in AuthorizeHelpers.person_tag_type_common_roles(api,caller,tag_type): reason="user not in slice; or slice does not belong to pi's site" @@ -202,7 +202,7 @@ def caller_may_write_slice_tag (slice, api, caller, tag_type, node_id_or_hostnam if not granted: # try: print "DEBUG: caller=%s"%caller # except: pass - raise PLCPermissionDenied, "Cannot write slice tag %s - %s"%(tag_type['tagname'],reason) + raise PLCPermissionDenied("Cannot write slice tag %s - %s"%(tag_type['tagname'],reason)) setattr(Slice,'caller_may_write_tag',caller_may_write_slice_tag) diff --git a/PLC/Boot.py b/PLC/Boot.py index 001211e0..0f1bc28d 100644 --- a/PLC/Boot.py +++ b/PLC/Boot.py @@ -33,7 +33,7 @@ def notify_owners(method, node, message_id, if include_pis or include_techs: sites = Sites(method.api, [node['site_id']]) if not sites: - raise PLCAPIError, "No site associated with node" + raise PLCAPIError("No site associated with node") site = sites[0] persons = Persons(method.api, site['person_ids']) diff --git a/PLC/BootStates.py b/PLC/BootStates.py index 2bbcf0de..d58bb93f 100644 --- a/PLC/BootStates.py +++ b/PLC/BootStates.py @@ -25,12 +25,12 @@ class BootState(Row): def validate_boot_state(self, name): # Make sure name is not blank if not len(name): - raise PLCInvalidArgument, "Boot state must be specified" + raise PLCInvalidArgument("Boot state must be specified") # Make sure boot state does not already exist conflicts = BootStates(self.api, [name]) if conflicts: - raise PLCInvalidArgument, "Boot state name already in use" + raise PLCInvalidArgument("Boot state name already in use") return name diff --git a/PLC/ConfFiles.py b/PLC/ConfFiles.py index 32a1b54e..b71eb47c 100644 --- a/PLC/ConfFiles.py +++ b/PLC/ConfFiles.py @@ -144,7 +144,7 @@ class ConfFiles(Table): ", ".join(self.columns) if conf_file_filter is not None: - if isinstance(conf_file_filter, (list, tuple, set, int, long)): + if isinstance(conf_file_filter, (list, tuple, set, int)): conf_file_filter = Filter(ConfFile.fields, {'conf_file_id': conf_file_filter}) elif isinstance(conf_file_filter, dict): conf_file_filter = Filter(ConfFile.fields, conf_file_filter) diff --git a/PLC/Config.py b/PLC/Config.py index c1dbe70f..78c15093 100644 --- a/PLC/Config.py +++ b/PLC/Config.py @@ -29,11 +29,11 @@ class Config: def __init__(self, file = "/etc/planetlab/plc_config"): # Load plc_config try: - execfile(file, self.__dict__) + exec(compile(open(file).read(), file, 'exec'), self.__dict__) except: # Try myplc directory try: - execfile(myplc + os.sep + "plc_config", self.__dict__) + exec(compile(open(myplc + os.sep + "plc_config").read(), myplc + os.sep + "plc_config", 'exec'), self.__dict__) except: raise PLCAPIError("Could not find plc_config in " + \ file + ", " + \ @@ -64,8 +64,8 @@ class XMLConfig: file + ", " + \ myplc + os.sep + "plc_config.xml") - for (category, variablelist) in cfg.variables().values(): - for variable in variablelist.values(): + for (category, variablelist) in list(cfg.variables().values()): + for variable in list(variablelist.values()): # Try to cast each variable to an appropriate Python # type. if variable['type'] == "int": @@ -91,4 +91,4 @@ class XMLConfig: if __name__ == '__main__': import pprint pprint = pprint.PrettyPrinter() - pprint.pprint(Config().__dict__.items()) + pprint.pprint(list(Config().__dict__.items())) diff --git a/PLC/Debug.py b/PLC/Debug.py index b120871a..9dba598f 100644 --- a/PLC/Debug.py +++ b/PLC/Debug.py @@ -28,8 +28,8 @@ def profile(callable): start = time.time() result = callable(*args, **kwds) end = time.time() - args = map(str, args) - args += ["%s = %s" % (name, str(value)) for (name, value) in kwds.items()] + args = list(map(str, args)) + args += ["%s = %s" % (name, str(value)) for (name, value) in list(kwds.items())] logger.info("%s (%s): %f s" % (callable.__name__, ", ".join(args), end - start)) return result diff --git a/PLC/EventObjects.py b/PLC/EventObjects.py index 5f046bf2..6dc45731 100644 --- a/PLC/EventObjects.py +++ b/PLC/EventObjects.py @@ -44,13 +44,13 @@ class EventObjects(Table): ", ".join(self.columns) if event_filter is not None: - if isinstance(event_filter, (list, tuple, set, int, long)): + if isinstance(event_filter, (list, tuple, set, int)): event_filter = Filter(EventObject.fields, {'event_id': event_filter}) sql += " AND (%s) %s" % event_filter.sql(api, "OR") elif isinstance(event_filter, dict): event_filter = Filter(EventObject.fields, event_filter) sql += " AND (%s) %s" % event_filter.sql(api, "AND") else: - raise PLCInvalidArgument, "Wrong event object filter %r"%event_filter + raise PLCInvalidArgument("Wrong event object filter %r"%event_filter) self.selectall(sql) diff --git a/PLC/Events.py b/PLC/Events.py index cb5d0e24..e006694c 100644 --- a/PLC/Events.py +++ b/PLC/Events.py @@ -67,11 +67,11 @@ class Events(Table): ", ".join(self.columns) if event_filter is not None: - if isinstance(event_filter, (list, tuple, set, int, long)): + if isinstance(event_filter, (list, tuple, set, int)): event_filter = Filter(Event.fields, {'event_id': event_filter}) elif isinstance(event_filter, dict): event_filter = Filter(Event.fields, event_filter) else: - raise PLCInvalidArgument, "Wrong event object filter %r"%event_filter + raise PLCInvalidArgument("Wrong event object filter %r"%event_filter) sql += " AND (%s) %s" % event_filter.sql(api) self.selectall(sql) diff --git a/PLC/Faults.py b/PLC/Faults.py index cebe5c5e..d4570311 100644 --- a/PLC/Faults.py +++ b/PLC/Faults.py @@ -7,13 +7,13 @@ # Copyright (C) 2004-2006 The Trustees of Princeton University # -import xmlrpclib +import xmlrpc.client -class PLCFault(xmlrpclib.Fault): +class PLCFault(xmlrpc.client.Fault): def __init__(self, faultCode, faultString, extra = None): if extra: faultString += ": " + extra - xmlrpclib.Fault.__init__(self, faultCode, faultString) + xmlrpc.client.Fault.__init__(self, faultCode, faultString) class PLCInvalidAPIMethod(PLCFault): def __init__(self, method, role = None, extra = None): diff --git a/PLC/Filter.py b/PLC/Filter.py index d3a17b4e..5c455720 100644 --- a/PLC/Filter.py +++ b/PLC/Filter.py @@ -104,7 +104,7 @@ class Filter(Parameter, dict): # either a value or a list of values for each of the specified # fields. self.fields = dict ( [ ( field, Mixed (expected, [expected])) - for (field,expected) in fields.iteritems() ] ) + for (field,expected) in fields.items() ] ) # Null filter means no filter Parameter.__init__(self, self.fields, doc = doc, nullok = True) @@ -114,10 +114,10 @@ class Filter(Parameter, dict): Returns a SQL conditional that represents this filter. """ - if self.has_key('-AND'): + if '-AND' in self: del self['-AND'] join_with='AND' - if self.has_key('-OR'): + if '-OR' in self: del self['-OR'] join_with='OR' @@ -135,7 +135,7 @@ class Filter(Parameter, dict): sorts = [] clips = [] - for field, value in self.iteritems(): + for field, value in self.items(): # handle negation, numeric comparisons # simple, 1-depth only mechanism @@ -146,7 +146,7 @@ class Filter(Parameter, dict): '&' : False, '|' : False, } def check_modifiers(field): - if field[0] in modifiers.keys(): + if field[0] in list(modifiers.keys()): modifiers[field[0]] = True field = field[1:] return check_modifiers(field) @@ -156,7 +156,7 @@ class Filter(Parameter, dict): # filter on fields if not modifiers['-']: if field not in self.fields: - raise PLCInvalidArgument, "Invalid filter field '%s'" % field + raise PLCInvalidArgument("Invalid filter field '%s'" % field) # handling array fileds always as compound values if modifiers['&'] or modifiers['|']: @@ -212,7 +212,7 @@ class Filter(Parameter, dict): else: vals[base_op] = [val] subclauses = [] - for operator in vals.keys(): + for operator in list(vals.keys()): if operator == '=': if modifiers['&']: subclauses.append("(%s @> ARRAY[%s])" % (field, ",".join(vals[operator]))) @@ -238,7 +238,7 @@ class Filter(Parameter, dict): # sorting and clipping else: if field not in ('SORT','OFFSET','LIMIT'): - raise PLCInvalidArgument, "Invalid filter, unknown sort and clip field %r"%field + raise PLCInvalidArgument("Invalid filter, unknown sort and clip field %r"%field) # sorting if field == 'SORT': if not isinstance(value,(list,tuple,set)): @@ -251,7 +251,7 @@ class Filter(Parameter, dict): field = field[1:] order = 'DESC' if field not in self.fields: - raise PLCInvalidArgument, "Invalid field %r in SORT filter"%field + raise PLCInvalidArgument("Invalid field %r in SORT filter"%field) sorts.append("%s %s"%(field,order)) # clipping elif field == 'OFFSET': diff --git a/PLC/GPG.py b/PLC/GPG.py index 1dcc0cf4..270bc453 100644 --- a/PLC/GPG.py +++ b/PLC/GPG.py @@ -9,10 +9,10 @@ # import os -import xmlrpclib +import xmlrpc.client import shutil from types import StringTypes -from StringIO import StringIO +from io import StringIO from subprocess import Popen, PIPE, call from tempfile import NamedTemporaryFile, mkdtemp from lxml import etree @@ -26,7 +26,7 @@ def canonicalize(args, methodname = None, methodresponse = False): True). """ - xml = xmlrpclib.dumps(args, methodname, methodresponse, encoding = 'utf-8', allow_none = 1) + xml = xmlrpc.client.dumps(args, methodname, methodresponse, encoding = 'utf-8', allow_none = 1) dom = etree.fromstring(xml) canonical=etree.tostring(dom) # pre-f20 version was using Canonicalize from PyXML @@ -59,7 +59,7 @@ def gpg_export(keyring, armor = True): shutil.rmtree(homedir) if rc: - raise PLCAuthenticationFailure, "GPG export failed with return code %d: %s" % (rc, err) + raise PLCAuthenticationFailure("GPG export failed with return code %d: %s" % (rc, err)) return export @@ -107,7 +107,7 @@ def gpg_sign(args, secret_keyring, keyring, methodname = None, methodresponse = shutil.rmtree(homedir) if rc: - raise PLCAuthenticationFailure, "GPG signing failed with return code %d: %s" % (rc, err) + raise PLCAuthenticationFailure("GPG signing failed with return code %d: %s" % (rc, err)) return signature @@ -173,6 +173,6 @@ def gpg_verify(args, key, signature = None, methodname = None, methodresponse = keyfile.close() if rc: - raise PLCAuthenticationFailure, "GPG verification failed with return code %d: %s" % (rc, err) + raise PLCAuthenticationFailure("GPG verification failed with return code %d: %s" % (rc, err)) return message diff --git a/PLC/Ilinks.py b/PLC/Ilinks.py index d99f13c2..1ef7df64 100644 --- a/PLC/Ilinks.py +++ b/PLC/Ilinks.py @@ -37,12 +37,12 @@ class Ilinks(Table): ", ".join(self.columns) if ilink_filter is not None: - if isinstance(ilink_filter, (list, tuple, set, int, long)): + if isinstance(ilink_filter, (list, tuple, set, int)): ilink_filter = Filter(Ilink.fields, {'ilink_id': ilink_filter}) elif isinstance(ilink_filter, dict): ilink_filter = Filter(Ilink.fields, ilink_filter) else: - raise PLCInvalidArgument, "Wrong ilink filter %r"%ilink_filter + raise PLCInvalidArgument("Wrong ilink filter %r"%ilink_filter) sql += " AND (%s) %s" % ilink_filter.sql(api) diff --git a/PLC/InitScripts.py b/PLC/InitScripts.py index c248c83c..f7cb0b56 100644 --- a/PLC/InitScripts.py +++ b/PLC/InitScripts.py @@ -35,7 +35,7 @@ class InitScript(Row): conflicts = InitScripts(self.api, [name]) for initscript in conflicts: if 'initscript_id' not in self or self['initscript_id'] != initscript['initscript_id']: - raise PLCInvalidArgument, "Initscript name already in use" + raise PLCInvalidArgument("Initscript name already in use") return name @@ -54,20 +54,20 @@ class InitScripts(Table): if initscript_filter is not None: if isinstance(initscript_filter, (list, tuple, set)): # Separate the list into integers and strings - ints = filter(lambda x: isinstance(x, (int, long)), initscript_filter) - strs = filter(lambda x: isinstance(x, StringTypes), initscript_filter) + ints = [x for x in initscript_filter if isinstance(x, int)] + strs = [x for x in initscript_filter if isinstance(x, StringTypes)] initscript_filter = Filter(InitScript.fields, {'initscript_id': ints, 'name': strs }) sql += " AND (%s) %s" % initscript_filter.sql(api, "OR") elif isinstance(initscript_filter, dict): initscript_filter = Filter(InitScript.fields, initscript_filter) sql += " AND (%s) %s" % initscript_filter.sql(api, "AND") - elif isinstance(initscript_filter, (int, long)): + elif isinstance(initscript_filter, int): initscript_filter = Filter(InitScript.fields, {'initscript_id': initscript_filter}) sql += " AND (%s) %s" % initscript_filter.sql(api, "AND") elif isinstance(initscript_filter, StringTypes): initscript_filter = Filter(InitScript.fields, {'name': initscript_filter}) sql += " AND (%s) %s" % initscript_filter.sql(api, "AND") else: - raise PLCInvalidArgument, "Wrong initscript filter %r"%initscript_filter + raise PLCInvalidArgument("Wrong initscript filter %r"%initscript_filter) self.selectall(sql) diff --git a/PLC/InterfaceTags.py b/PLC/InterfaceTags.py index af1deb46..dca2d2a2 100644 --- a/PLC/InterfaceTags.py +++ b/PLC/InterfaceTags.py @@ -42,12 +42,12 @@ class InterfaceTags(Table): ", ".join(self.columns) if interface_tag_filter is not None: - if isinstance(interface_tag_filter, (list, tuple, set, int, long)): + if isinstance(interface_tag_filter, (list, tuple, set, int)): interface_tag_filter = Filter(InterfaceTag.fields, {'interface_tag_id': interface_tag_filter}) elif isinstance(interface_tag_filter, dict): interface_tag_filter = Filter(InterfaceTag.fields, interface_tag_filter) else: - raise PLCInvalidArgument, "Wrong interface setting filter %r"%interface_tag_filter + raise PLCInvalidArgument("Wrong interface setting filter %r"%interface_tag_filter) sql += " AND (%s) %s" % interface_tag_filter.sql(api) diff --git a/PLC/Interfaces.py b/PLC/Interfaces.py index 0e6c7287..07c351d8 100644 --- a/PLC/Interfaces.py +++ b/PLC/Interfaces.py @@ -97,18 +97,18 @@ class Interface(Row): def validate_method(self, method): network_methods = [row['method'] for row in NetworkMethods(self.api)] if method not in network_methods: - raise PLCInvalidArgument, "Invalid addressing method %s"%method + raise PLCInvalidArgument("Invalid addressing method %s"%method) return method def validate_type(self, type): network_types = [row['type'] for row in NetworkTypes(self.api)] if type not in network_types: - raise PLCInvalidArgument, "Invalid address type %s"%type + raise PLCInvalidArgument("Invalid address type %s"%type) return type def validate_ip(self, ip): if ip and not valid_ip(ip): - raise PLCInvalidArgument, "Invalid IP address %s"%ip + raise PLCInvalidArgument("Invalid IP address %s"%ip) return ip def validate_mac(self, mac): @@ -126,7 +126,7 @@ class Interface(Row): bytes[i] = "%02x" % byte mac = ":".join(bytes) except: - raise PLCInvalidArgument, "Invalid MAC address %s"%mac + raise PLCInvalidArgument("Invalid MAC address %s"%mac) return mac @@ -142,7 +142,7 @@ class Interface(Row): return bwlimit if bwlimit < 500000: - raise PLCInvalidArgument, 'Minimum bw is 500 kbs' + raise PLCInvalidArgument('Minimum bw is 500 kbs') return bwlimit @@ -152,14 +152,14 @@ class Interface(Row): return hostname if not PLC.Nodes.valid_hostname(hostname): - raise PLCInvalidArgument, "Invalid hostname %s"%hostname + raise PLCInvalidArgument("Invalid hostname %s"%hostname) return hostname def validate_node_id(self, node_id): nodes = PLC.Nodes.Nodes(self.api, [node_id]) if not nodes: - raise PLCInvalidArgument, "No such node %d"%node_id + raise PLCInvalidArgument("No such node %d"%node_id) return node_id @@ -171,7 +171,7 @@ class Interface(Row): if is_primary: nodes = PLC.Nodes.Nodes(self.api, [self['node_id']]) if not nodes: - raise PLCInvalidArgument, "No such node %d"%node_id + raise PLCInvalidArgument("No such node %d"%node_id) node = nodes[0] if node['interface_ids']: @@ -180,7 +180,7 @@ class Interface(Row): if ('interface_id' not in self or \ self['interface_id'] != interface['interface_id']) and \ interface['is_primary']: - raise PLCInvalidArgument, "Can only set one primary interface per node" + raise PLCInvalidArgument("Can only set one primary interface per node") return is_primary @@ -197,12 +197,12 @@ class Interface(Row): if method == "proxy" or method == "tap": if 'mac' in self and self['mac']: - raise PLCInvalidArgument, "For %s method, mac should not be specified" % method + raise PLCInvalidArgument("For %s method, mac should not be specified" % method) if 'ip' not in self or not self['ip']: - raise PLCInvalidArgument, "For %s method, ip is required" % method + raise PLCInvalidArgument("For %s method, ip is required" % method) if method == "tap" and ('gateway' not in self or not self['gateway']): - raise PLCInvalidArgument, "For tap method, gateway is required and should be " \ - "the IP address of the node that proxies for this address" + raise PLCInvalidArgument("For tap method, gateway is required and should be " \ + "the IP address of the node that proxies for this address") # Should check that the proxy address is reachable, but # there's no way to tell if the only primary interface is # DHCP! @@ -212,30 +212,30 @@ class Interface(Row): for key in ['gateway', 'dns1']: if key not in self or not self[key]: if 'is_primary' in self and self['is_primary'] is True: - raise PLCInvalidArgument, "For static method primary network, %s is required" % key + raise PLCInvalidArgument("For static method primary network, %s is required" % key) else: globals()[key] = self[key] for key in ['ip', 'network', 'broadcast', 'netmask']: if key not in self or not self[key]: - raise PLCInvalidArgument, "For static method, %s is required" % key + raise PLCInvalidArgument("For static method, %s is required" % key) globals()[key] = self[key] if not in_same_network(ip, network, netmask): - raise PLCInvalidArgument, "IP address %s is inconsistent with network %s/%s" % \ - (ip, network, netmask) + raise PLCInvalidArgument("IP address %s is inconsistent with network %s/%s" % \ + (ip, network, netmask)) if not in_same_network(broadcast, network, netmask): - raise PLCInvalidArgument, "Broadcast address %s is inconsistent with network %s/%s" % \ - (broadcast, network, netmask) + raise PLCInvalidArgument("Broadcast address %s is inconsistent with network %s/%s" % \ + (broadcast, network, netmask)) if 'gateway' in globals() and not in_same_network(ip, gateway, netmask): - raise PLCInvalidArgument, "Gateway %s is not reachable from %s/%s" % \ - (gateway, ip, netmask) + raise PLCInvalidArgument("Gateway %s is not reachable from %s/%s" % \ + (gateway, ip, netmask)) elif self['type'] == 'ipv6': for key in ['ip', 'gateway']: if key not in self or not self[key]: - raise PLCInvalidArgument, "For static ipv6 method, %s is required" % key + raise PLCInvalidArgument("For static ipv6 method, %s is required" % key) globals()[key] = self[key] elif method == "ipmi": if 'ip' not in self or not self['ip']: - raise PLCInvalidArgument, "For ipmi method, ip is required" + raise PLCInvalidArgument("For ipmi method, ip is required") validate_last_updated = Row.validate_timestamp @@ -278,17 +278,17 @@ class Interfaces(Table): Interface.primary_key) sql = "SELECT %s FROM %s WHERE True" % \ - (", ".join(self.columns.keys()+self.tag_columns.keys()),view) + (", ".join(list(self.columns.keys())+list(self.tag_columns.keys())),view) if interface_filter is not None: if isinstance(interface_filter, (list, tuple, set)): # Separate the list into integers and strings - ints = filter(lambda x: isinstance(x, (int, long)), interface_filter) - strs = filter(lambda x: isinstance(x, StringTypes), interface_filter) + ints = [x for x in interface_filter if isinstance(x, int)] + strs = [x for x in interface_filter if isinstance(x, StringTypes)] interface_filter = Filter(Interface.fields, {'interface_id': ints, 'ip': strs}) sql += " AND (%s) %s" % interface_filter.sql(api, "OR") elif isinstance(interface_filter, dict): - allowed_fields=dict(Interface.fields.items()+Interface.tags.items()) + allowed_fields=dict(list(Interface.fields.items())+list(Interface.tags.items())) interface_filter = Filter(allowed_fields, interface_filter) sql += " AND (%s) %s" % interface_filter.sql(api) elif isinstance(interface_filter, int): @@ -298,6 +298,6 @@ class Interfaces(Table): interface_filter = Filter(Interface.fields, {'ip':[interface_filter]}) sql += " AND (%s) %s" % interface_filter.sql(api, "AND") else: - raise PLCInvalidArgument, "Wrong interface filter %r"%interface_filter + raise PLCInvalidArgument("Wrong interface filter %r"%interface_filter) self.selectall(sql) diff --git a/PLC/KeyTypes.py b/PLC/KeyTypes.py index df15643b..e2344557 100644 --- a/PLC/KeyTypes.py +++ b/PLC/KeyTypes.py @@ -25,12 +25,12 @@ class KeyType(Row): def validate_key_type(self, name): # Make sure name is not blank if not len(name): - raise PLCInvalidArgument, "Key type must be specified" + raise PLCInvalidArgument("Key type must be specified") # Make sure key type does not alredy exist conflicts = KeyTypes(self.api, [name]) if conflicts: - raise PLCInvalidArgument, "Key type name already in use" + raise PLCInvalidArgument("Key type name already in use") return name diff --git a/PLC/Keys.py b/PLC/Keys.py index ebabd190..1103f7cf 100644 --- a/PLC/Keys.py +++ b/PLC/Keys.py @@ -29,7 +29,7 @@ class Key(Row): def validate_key_type(self, key_type): key_types = [row['key_type'] for row in KeyTypes(self.api)] if key_type not in key_types: - raise PLCInvalidArgument, "Invalid key type" + raise PLCInvalidArgument("Invalid key type") return key_type def validate_key(self, key): @@ -39,7 +39,7 @@ class Key(Row): " AND is_blacklisted IS True", locals()) if rows: - raise PLCInvalidArgument, "Key is blacklisted and cannot be used" + raise PLCInvalidArgument("Key is blacklisted and cannot be used") return key @@ -63,7 +63,7 @@ class Key(Row): good_ssh_key = r'^.*(?:ssh-dss|ssh-rsa)[ ]+[A-Za-z0-9+/=]+(?: .*)?$' if not re.match(good_ssh_key, key, re.IGNORECASE): - raise PLCInvalidArgument, "Invalid SSH version 2 public key" + raise PLCInvalidArgument("Invalid SSH version 2 public key") def blacklist(self, commit = True): """ @@ -108,12 +108,12 @@ class Keys(Table): ", ".join(self.columns) if key_filter is not None: - if isinstance(key_filter, (list, tuple, set, int, long)): + if isinstance(key_filter, (list, tuple, set, int)): key_filter = Filter(Key.fields, {'key_id': key_filter}) elif isinstance(key_filter, dict): key_filter = Filter(Key.fields, key_filter) else: - raise PLCInvalidArgument, "Wrong key filter %r"%key_filter + raise PLCInvalidArgument("Wrong key filter %r"%key_filter) sql += " AND (%s) %s" % key_filter.sql(api) self.selectall(sql) diff --git a/PLC/LDAP.py b/PLC/LDAP.py index da54456b..86250125 100644 --- a/PLC/LDAP.py +++ b/PLC/LDAP.py @@ -4,7 +4,7 @@ # Copyright (C) 2006 The Trustees of Princeton University # -import ldap +from . import ldap import traceback from PLC.Debug import profile from PLC.Faults import * @@ -35,8 +35,8 @@ class LDAP: self.connection.bind(dn, pw, ldap.AUTH_SIMPLE) else: self.connection.bind_s(dn, pw, ldap.AUTH_SIMPLE) - except ldap.LDAPError, e: - raise PLCLDAPError, "Unable to bind to server: %s" % e + except ldap.LDAPError as e: + raise PLCLDAPError("Unable to bind to server: %s" % e) return connection def close(self): @@ -66,7 +66,7 @@ class LDAP: def to_ldap_filter(search_filter): search_filter = pl_to_ldap(search_filter) values = [] - for (key,value) in search_filter.items(): + for (key,value) in list(search_filter.items()): values.append("(%s=%s)" % (key,value)) return "(&%s)" % "".join(values) diff --git a/PLC/LeaseFilter.py b/PLC/LeaseFilter.py index e192d435..20078fca 100644 --- a/PLC/LeaseFilter.py +++ b/PLC/LeaseFilter.py @@ -135,7 +135,7 @@ class LeaseFilter (Filter): # self.negation is a dict local_key : string self.local = {} self.negation = {} - for (k, v) in LeaseFilter.local_fields.items(): + for (k, v) in list(LeaseFilter.local_fields.items()): if k in self: self.local[k] = self[k] del self[k] @@ -146,7 +146,7 @@ class LeaseFilter (Filter): self.negation[k] = "NOT " # run the generic filtering code (where_part, clip_part) = Filter.sql(self, api, join_with) - for (k, v) in self.local.items(): + for (k, v) in list(self.local.items()): try: # locate hook function associated with key method = LeaseFilter.__dict__['sql_' + k] @@ -154,7 +154,7 @@ class LeaseFilter (Filter): .format(self.join_with, self.negation[k], method(self, self.local[k])) - except Exception, e: + except Exception as e: raise PLCInvalidArgument( "LeaseFilter: something wrong with filter" "key {}, val was {} -- {}".format(k, v, e)) diff --git a/PLC/Leases.py b/PLC/Leases.py index c1b2235a..66e79029 100644 --- a/PLC/Leases.py +++ b/PLC/Leases.py @@ -75,16 +75,16 @@ class Leases(Table): # the view that we're selecting upon: start with view_leases view = "view_leases" - sql = "SELECT %s FROM %s WHERE true" % (", ".join(self.columns.keys()),view) + sql = "SELECT %s FROM %s WHERE true" % (", ".join(list(self.columns.keys())),view) if lease_filter is not None: - if isinstance(lease_filter, (list, tuple, set, int, long)): + if isinstance(lease_filter, (list, tuple, set, int)): lease_filter = Filter(Lease.fields, {'lease_id': lease_filter}) elif isinstance(lease_filter, dict): lease_filter = LeaseFilter(Lease.fields, lease_filter) else: - raise PLCInvalidArgument, "Wrong lease filter %r"%lease_filter + raise PLCInvalidArgument("Wrong lease filter %r"%lease_filter) sql += " AND (%s) %s" % lease_filter.sql(api) self.selectall(sql) diff --git a/PLC/Messages.py b/PLC/Messages.py index 36969267..e1c87400 100644 --- a/PLC/Messages.py +++ b/PLC/Messages.py @@ -38,13 +38,13 @@ class Messages(Table): sql += " AND enabled IS %s" % enabled if message_filter is not None: - if isinstance(message_filter, (list, tuple, set, int, long)): + if isinstance(message_filter, (list, tuple, set, int)): message_filter = Filter(Message.fields, {'message_id': message_filter}) sql += " AND (%s) %s" % message_filter.sql(api, "OR") elif isinstance(message_filter, dict): message_filter = Filter(Message.fields, message_filter) sql += " AND (%s) %s" % message_filter.sql(api, "AND") else: - raise PLCInvalidArgument, "Wrong message filter %r"%message_filter + raise PLCInvalidArgument("Wrong message filter %r"%message_filter) self.selectall(sql) diff --git a/PLC/Method.py b/PLC/Method.py index 571c3ebe..8e9fb203 100644 --- a/PLC/Method.py +++ b/PLC/Method.py @@ -4,7 +4,7 @@ # Mark Huang # Copyright (C) 2006 The Trustees of Princeton University # -import xmlrpclib +import xmlrpc.client from types import * import textwrap import os @@ -104,7 +104,7 @@ class Method (object): return result - except PLCFault, fault: + except PLCFault as fault: caller = "" if isinstance(self.caller, Person): @@ -151,13 +151,13 @@ class Method (object): newargs.append(arg) continue # what type of auth this is - if arg.has_key('AuthMethod'): + if 'AuthMethod' in arg: auth_methods = ['session', 'password', 'capability', 'gpg', 'hmac','anonymous'] auth_method = arg['AuthMethod'] if auth_method in auth_methods: event['auth_type'] = auth_method for password in 'AuthString', 'session', 'password': - if arg.has_key(password): + if password in arg: arg = arg.copy() arg[password] = "Removed by API" newargs.append(arg) @@ -176,7 +176,7 @@ class Method (object): event.sync(commit = False) if hasattr(self, 'event_objects') and isinstance(self.event_objects, dict): - for key in self.event_objects.keys(): + for key in list(self.event_objects.keys()): for object_id in self.event_objects[key]: event.add_object(key, object_id, commit = False) @@ -240,7 +240,7 @@ class Method (object): # 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: @@ -273,8 +273,8 @@ class Method (object): """ # 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 = () @@ -305,7 +305,7 @@ class Method (object): try: self.type_check(name, value, item, args) return - except PLCInvalidArgument, fault: + except PLCInvalidArgument as fault: pass raise fault @@ -353,20 +353,20 @@ class Method (object): if expected_type in StringTypes: if min is not None and \ len(value.encode(self.api.encoding)) < min: - raise PLCInvalidArgument, "%s must be at least %d bytes long" % (name, min) + raise PLCInvalidArgument("%s must be at least %d bytes long" % (name, min)) if max is not None and \ len(value.encode(self.api.encoding)) > max: - raise PLCInvalidArgument, "%s must be at most %d bytes long" % (name, max) + raise PLCInvalidArgument("%s must be at most %d bytes long" % (name, max)) elif expected_type in (list, tuple, set): if min is not None and len(value) < min: - raise PLCInvalidArgument, "%s must contain at least %d items" % (name, min) + raise PLCInvalidArgument("%s must contain at least %d items" % (name, min)) if max is not None and len(value) > max: - raise PLCInvalidArgument, "%s must contain at most %d items" % (name, max) + raise PLCInvalidArgument("%s must contain at most %d items" % (name, max)) else: if min is not None and value < min: - raise PLCInvalidArgument, "%s must be > %s" % (name, str(min)) + raise PLCInvalidArgument("%s must be > %s" % (name, str(min))) if max is not None and value > max: - raise PLCInvalidArgument, "%s must be < %s" % (name, str(max)) + raise PLCInvalidArgument("%s must be < %s" % (name, str(max))) # If a list with particular types of items is expected if isinstance(expected, (list, tuple, set)): @@ -380,13 +380,13 @@ class Method (object): # 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 PLCInvalidArgument("'%s' not specified" % key, name) if auth is not None: diff --git a/PLC/Methods/AddAddressType.py b/PLC/Methods/AddAddressType.py index 28477141..2f8d4182 100644 --- a/PLC/Methods/AddAddressType.py +++ b/PLC/Methods/AddAddressType.py @@ -4,7 +4,7 @@ from PLC.Parameter import Parameter, Mixed from PLC.AddressTypes import AddressType, AddressTypes from PLC.Auth import Auth -can_update = lambda (field, value): field not in ['address_type_id'] +can_update = lambda field_value: field_value[0] not in ['address_type_id'] class AddAddressType(Method): """ @@ -16,7 +16,7 @@ class AddAddressType(Method): roles = ['admin'] - address_type_fields = dict(filter(can_update, AddressType.fields.items())) + address_type_fields = dict(list(filter(can_update, list(AddressType.fields.items())))) accepts = [ Auth(), @@ -27,7 +27,7 @@ class AddAddressType(Method): def call(self, auth, address_type_fields): - address_type_fields = dict(filter(can_update, address_type_fields.items())) + address_type_fields = dict(list(filter(can_update, list(address_type_fields.items())))) address_type = AddressType(self.api, address_type_fields) address_type.sync() diff --git a/PLC/Methods/AddAddressTypeToAddress.py b/PLC/Methods/AddAddressTypeToAddress.py index 99ddfe4f..8dd37ac3 100644 --- a/PLC/Methods/AddAddressTypeToAddress.py +++ b/PLC/Methods/AddAddressTypeToAddress.py @@ -29,17 +29,17 @@ class AddAddressTypeToAddress(Method): def call(self, auth, address_type_id_or_name, address_id): address_types = AddressTypes(self.api, [address_type_id_or_name]) if not address_types: - raise PLCInvalidArgument, "No such address type" + raise PLCInvalidArgument("No such address type") address_type = address_types[0] addresses = Addresses(self.api, [address_id]) if not addresses: - raise PLCInvalidArgument, "No such address" + raise PLCInvalidArgument("No such address") address = addresses[0] if 'admin' not in self.caller['roles']: if address['site_id'] not in self.caller['site_ids']: - raise PLCPermissionDenied, "Address must be associated with one of your sites" + raise PLCPermissionDenied("Address must be associated with one of your sites") address.add_address_type(address_type) self.event_objects = {'Address': [address['address_id']]} diff --git a/PLC/Methods/AddConfFile.py b/PLC/Methods/AddConfFile.py index 6e4fe8bd..cb9200d6 100644 --- a/PLC/Methods/AddConfFile.py +++ b/PLC/Methods/AddConfFile.py @@ -4,7 +4,7 @@ from PLC.Parameter import Parameter, Mixed from PLC.ConfFiles import ConfFile, ConfFiles from PLC.Auth import Auth -can_update = lambda (field, value): field not in \ +can_update = lambda field_value: field_value[0] not in \ ['conf_file_id', 'node_ids', 'nodegroup_ids'] class AddConfFile(Method): @@ -17,7 +17,7 @@ class AddConfFile(Method): roles = ['admin'] - conf_file_fields = dict(filter(can_update, ConfFile.fields.items())) + conf_file_fields = dict(list(filter(can_update, list(ConfFile.fields.items())))) accepts = [ Auth(), @@ -28,7 +28,7 @@ class AddConfFile(Method): def call(self, auth, conf_file_fields): - conf_file_fields = dict(filter(can_update, conf_file_fields.items())) + conf_file_fields = dict(list(filter(can_update, list(conf_file_fields.items())))) conf_file = ConfFile(self.api, conf_file_fields) conf_file.sync() diff --git a/PLC/Methods/AddConfFileToNode.py b/PLC/Methods/AddConfFileToNode.py index eeb9af58..404b8e21 100644 --- a/PLC/Methods/AddConfFileToNode.py +++ b/PLC/Methods/AddConfFileToNode.py @@ -28,17 +28,17 @@ class AddConfFileToNode(Method): # Get configuration file conf_files = ConfFiles(self.api, [conf_file_id]) if not conf_files: - raise PLCInvalidArgument, "No such configuration file" + raise PLCInvalidArgument("No such configuration file") conf_file = conf_files[0] # Get node nodes = Nodes(self.api, [node_id_or_hostname]) if not nodes: - raise PLCInvalidArgument, "No such node" + raise PLCInvalidArgument("No such node") node = nodes[0] if node['peer_id'] is not None: - raise PLCInvalidArgument, "Not a local node" + raise PLCInvalidArgument("Not a local node") # Link configuration file to node if node['node_id'] not in conf_file['node_ids']: diff --git a/PLC/Methods/AddConfFileToNodeGroup.py b/PLC/Methods/AddConfFileToNodeGroup.py index 892e64f3..8b42f082 100644 --- a/PLC/Methods/AddConfFileToNodeGroup.py +++ b/PLC/Methods/AddConfFileToNodeGroup.py @@ -30,13 +30,13 @@ class AddConfFileToNodeGroup(Method): # Get configuration file conf_files = ConfFiles(self.api, [conf_file_id]) if not conf_files: - raise PLCInvalidArgument, "No such configuration file" + raise PLCInvalidArgument("No such configuration file") conf_file = conf_files[0] # Get node nodegroups = NodeGroups(self.api, [nodegroup_id_or_name]) if not nodegroups: - raise PLCInvalidArgument, "No such node group" + raise PLCInvalidArgument("No such node group") nodegroup = nodegroups[0] # Link configuration file to node diff --git a/PLC/Methods/AddIlink.py b/PLC/Methods/AddIlink.py index 0a7066a4..1d623c8d 100644 --- a/PLC/Methods/AddIlink.py +++ b/PLC/Methods/AddIlink.py @@ -41,14 +41,14 @@ class AddIlink(Method): src_if = Interfaces (self.api, [src_if_id],['interface_id']) if not src_if: - raise PLCInvalidArgument, "No such source interface %r"%src_if_id + raise PLCInvalidArgument("No such source interface %r"%src_if_id) dst_if = Interfaces (self.api, [dst_if_id],['interface_id']) if not dst_if: - raise PLCInvalidArgument, "No such destination interface %r"%dst_if_id + raise PLCInvalidArgument("No such destination interface %r"%dst_if_id) tag_types = TagTypes(self.api, [tag_type_id_or_name]) if not tag_types: - raise PLCInvalidArgument, "AddIlink: No such tag type %r"%tag_type_id_or_name + raise PLCInvalidArgument("AddIlink: No such tag type %r"%tag_type_id_or_name) tag_type = tag_types[0] # checks for existence - with the same type @@ -59,20 +59,20 @@ class AddIlink(Method): if len(conflicts) : ilink=conflicts[0] - raise PLCInvalidArgument, "Ilink (%s,%d,%d) already exists and has value %r"\ - %(tag_type['name'],src_if_id,dst_if_id,ilink['value']) + raise PLCInvalidArgument("Ilink (%s,%d,%d) already exists and has value %r"\ + %(tag_type['name'],src_if_id,dst_if_id,ilink['value'])) # check authorizations if 'admin' in self.caller['roles']: pass elif not AuthorizeHelpers.caller_may_access_tag_type (self.api, self.caller, tag_type): - raise PLCPermissionDenied, "%s, forbidden tag %s"%(self.name,tag_type['tagname']) + raise PLCPermissionDenied("%s, forbidden tag %s"%(self.name,tag_type['tagname'])) elif AuthorizeHelpers.interface_belongs_to_person (self.api, src_if, self.caller): pass elif src_if_id != dst_if_id and AuthorizeHelpers.interface_belongs_to_person (self.api, dst_if, self.caller): pass else: - raise PLCPermissionDenied, "%s: you must one either the src or dst interface"%self.name + raise PLCPermissionDenied("%s: you must one either the src or dst interface"%self.name) ilink = Ilink(self.api) ilink['tag_type_id'] = tag_type['tag_type_id'] diff --git a/PLC/Methods/AddInitScript.py b/PLC/Methods/AddInitScript.py index 10f844fb..81b0d549 100644 --- a/PLC/Methods/AddInitScript.py +++ b/PLC/Methods/AddInitScript.py @@ -4,7 +4,7 @@ from PLC.Parameter import Parameter, Mixed from PLC.InitScripts import InitScript, InitScripts from PLC.Auth import Auth -can_update = lambda (field, value): field not in \ +can_update = lambda field_value: field_value[0] not in \ ['initscript_id'] class AddInitScript(Method): @@ -17,7 +17,7 @@ class AddInitScript(Method): roles = ['admin'] - initscript_fields = dict(filter(can_update, InitScript.fields.items())) + initscript_fields = dict(list(filter(can_update, list(InitScript.fields.items())))) accepts = [ Auth(), @@ -28,7 +28,7 @@ class AddInitScript(Method): def call(self, auth, initscript_fields): - initscript_fields = dict(filter(can_update, initscript_fields.items())) + initscript_fields = dict(list(filter(can_update, list(initscript_fields.items())))) initscript = InitScript(self.api, initscript_fields) initscript.sync() diff --git a/PLC/Methods/AddInterface.py b/PLC/Methods/AddInterface.py index ec35fc7b..ee07d1b3 100644 --- a/PLC/Methods/AddInterface.py +++ b/PLC/Methods/AddInterface.py @@ -55,12 +55,12 @@ class AddInterface(Method): # type checking native = Row.check_fields (native, self.accepted_fields) if rejected: - raise PLCInvalidArgument, "Cannot add Interface with column(s) %r"%rejected + raise PLCInvalidArgument("Cannot add Interface with column(s) %r"%rejected) # Check if node exists nodes = Nodes(self.api, [node_id_or_hostname]) if not nodes: - raise PLCInvalidArgument, "No such node %r"%node_id_or_hostname + raise PLCInvalidArgument("No such node %r"%node_id_or_hostname) node = nodes[0] # Authenticated function @@ -70,7 +70,7 @@ class AddInterface(Method): # member of the site where the node exists. if 'admin' not in self.caller['roles']: if node['site_id'] not in self.caller['site_ids']: - raise PLCPermissionDenied, "Not allowed to add an interface to the specified node" + raise PLCPermissionDenied("Not allowed to add an interface to the specified node") # Add interface interface = Interface(self.api, native) @@ -85,10 +85,10 @@ class AddInterface(Method): 'Interface' : [interface['interface_id']] } self.message = "Interface %d added" % interface['interface_id'] - for (tagname,value) in tags.iteritems(): + for (tagname,value) in tags.items(): # the tagtype instance is assumed to exist, just check that if not TagTypes(self.api,{'tagname':tagname}): - raise PLCInvalidArgument,"No such TagType %s"%tagname + raise PLCInvalidArgument("No such TagType %s"%tagname) interface_tags=InterfaceTags(self.api,{'tagname':tagname,'interface_id':interface['interface_id']}) if not interface_tags: AddInterfaceTag(self.api).__call__(auth,interface['interface_id'],tagname,value) diff --git a/PLC/Methods/AddInterfaceTag.py b/PLC/Methods/AddInterfaceTag.py index b02b4844..64a9375b 100644 --- a/PLC/Methods/AddInterfaceTag.py +++ b/PLC/Methods/AddInterfaceTag.py @@ -44,12 +44,12 @@ class AddInterfaceTag(Method): def call(self, auth, interface_id, tag_type_id_or_name, value): interfaces = Interfaces(self.api, [interface_id]) if not interfaces: - raise PLCInvalidArgument, "No such interface %r"%interface_id + raise PLCInvalidArgument("No such interface %r"%interface_id) interface = interfaces[0] tag_types = TagTypes(self.api, [tag_type_id_or_name]) if not tag_types: - raise PLCInvalidArgument, "No such tag type %r"%tag_type_id_or_name + raise PLCInvalidArgument("No such tag type %r"%tag_type_id_or_name) tag_type = tag_types[0] # checks for existence - does not allow several different settings @@ -58,8 +58,8 @@ class AddInterfaceTag(Method): 'tag_type_id':tag_type['tag_type_id']}) if len(conflicts) : - raise PLCInvalidArgument, "Interface %d already has setting %d"%(interface['interface_id'], - tag_type['tag_type_id']) + raise PLCInvalidArgument("Interface %d already has setting %d"%(interface['interface_id'], + tag_type['tag_type_id'])) # check authorizations interface.caller_may_write_tag(self.api,self.caller,tag_type) diff --git a/PLC/Methods/AddNode.py b/PLC/Methods/AddNode.py index 0ee13f5a..2be2176c 100644 --- a/PLC/Methods/AddNode.py +++ b/PLC/Methods/AddNode.py @@ -46,12 +46,12 @@ class AddNode(Method): # type checking native = Row.check_fields(native, self.accepted_fields) if rejected: - raise PLCInvalidArgument, "Cannot add Node with column(s) %r"%rejected + raise PLCInvalidArgument("Cannot add Node with column(s) %r"%rejected) # Get site information sites = Sites(self.api, [site_id_or_login_base]) if not sites: - raise PLCInvalidArgument, "No such site" + raise PLCInvalidArgument("No such site") site = sites[0] @@ -63,7 +63,7 @@ class AddNode(Method): if 'admin' not in self.caller['roles']: if site['site_id'] not in self.caller['site_ids']: assert self.caller['person_id'] not in site['person_ids'] - raise PLCPermissionDenied, "Not allowed to add nodes to specified site" + raise PLCPermissionDenied("Not allowed to add nodes to specified site") else: assert self.caller['person_id'] in site['person_ids'] @@ -76,11 +76,11 @@ class AddNode(Method): login_base = site['login_base'] tags['hrn'] = hostname_to_hrn(root_auth, login_base, node['hostname']) - for (tagname,value) in tags.iteritems(): + for (tagname,value) in tags.items(): # the tagtype instance is assumed to exist, just check that tag_types = TagTypes(self.api,{'tagname':tagname}) if not tag_types: - raise PLCInvalidArgument,"No such TagType %s"%tagname + raise PLCInvalidArgument("No such TagType %s"%tagname) tag_type = tag_types[0] node_tags=NodeTags(self.api,{'tagname':tagname,'node_id':node['node_id']}) if not node_tags: diff --git a/PLC/Methods/AddNodeGroup.py b/PLC/Methods/AddNodeGroup.py index a24fa8e7..2beed717 100644 --- a/PLC/Methods/AddNodeGroup.py +++ b/PLC/Methods/AddNodeGroup.py @@ -7,7 +7,7 @@ from PLC.NodeGroups import NodeGroup, NodeGroups from PLC.TagTypes import TagType, TagTypes from PLC.NodeTags import NodeTag, NodeTags -can_update = lambda (field, value): field in NodeGroup.fields.keys() and field != NodeGroup.primary_field +can_update = lambda field_value: field_value[0] in list(NodeGroup.fields.keys()) and field_value[0] != NodeGroup.primary_field class AddNodeGroup(Method): """ @@ -19,7 +19,7 @@ class AddNodeGroup(Method): roles = ['admin'] - nodegroup_fields = dict(filter(can_update, NodeGroup.fields.items())) + nodegroup_fields = dict(list(filter(can_update, list(NodeGroup.fields.items())))) accepts = [ Auth(), @@ -36,7 +36,7 @@ class AddNodeGroup(Method): # locate tag type tag_types = TagTypes (self.api,[tag_type_id_or_tagname]) if not(tag_types): - raise PLCInvalidArgument, "No such tag type %r"%tag_type_id_or_tagname + raise PLCInvalidArgument("No such tag type %r"%tag_type_id_or_tagname) tag_type=tag_types[0] nodegroup_fields = { 'groupname' : groupname, diff --git a/PLC/Methods/AddNodeTag.py b/PLC/Methods/AddNodeTag.py index 50801311..089dcfa6 100644 --- a/PLC/Methods/AddNodeTag.py +++ b/PLC/Methods/AddNodeTag.py @@ -44,12 +44,12 @@ class AddNodeTag(Method): def call(self, auth, node_id, tag_type_id_or_name, value): nodes = Nodes(self.api, [node_id]) if not nodes: - raise PLCInvalidArgument, "No such node %r"%node_id + raise PLCInvalidArgument("No such node %r"%node_id) node = nodes[0] tag_types = TagTypes(self.api, [tag_type_id_or_name]) if not tag_types: - raise PLCInvalidArgument, "No such node tag type %r"%tag_type_id_or_name + raise PLCInvalidArgument("No such node tag type %r"%tag_type_id_or_name) tag_type = tag_types[0] # checks for existence - does not allow several different tags @@ -58,8 +58,8 @@ class AddNodeTag(Method): 'tag_type_id':tag_type['tag_type_id']}) if len(conflicts) : - raise PLCInvalidArgument, "Node %d already has tag %d"%(node['node_id'], - tag_type['tag_type_id']) + raise PLCInvalidArgument("Node %d already has tag %d"%(node['node_id'], + tag_type['tag_type_id'])) # check authorizations node.caller_may_write_tag(self.api,self.caller,tag_type) diff --git a/PLC/Methods/AddNodeToPCU.py b/PLC/Methods/AddNodeToPCU.py index 72ed8a50..29044569 100644 --- a/PLC/Methods/AddNodeToPCU.py +++ b/PLC/Methods/AddNodeToPCU.py @@ -32,16 +32,16 @@ class AddNodeToPCU(Method): # Get node nodes = Nodes(self.api, [node_id_or_hostname]) if not nodes: - raise PLCInvalidArgument, "No such node" + raise PLCInvalidArgument("No such node") node = nodes[0] if node['peer_id'] is not None: - raise PLCInvalidArgument, "Not a local node" + raise PLCInvalidArgument("Not a local node") # Get PCU pcus = PCUs(self.api, [pcu_id]) if not pcus: - raise PLCInvalidArgument, "No such PCU" + raise PLCInvalidArgument("No such PCU") pcu = pcus[0] if 'admin' not in self.caller['roles']: @@ -52,17 +52,17 @@ class AddNodeToPCU(Method): ok = True break if not ok: - raise PLCPermissionDenied, "Not allowed to update that PCU" + raise PLCPermissionDenied("Not allowed to update that PCU") # Add node to PCU if node['node_id'] in pcu['node_ids']: - raise PLCInvalidArgument, "Node already controlled by PCU" + raise PLCInvalidArgument("Node already controlled by PCU") if node['site_id'] != pcu['site_id']: - raise PLCInvalidArgument, "Node is at a different site than this PCU" + raise PLCInvalidArgument("Node is at a different site than this PCU") if port in pcu['ports']: - raise PLCInvalidArgument, "PCU port already in use" + raise PLCInvalidArgument("PCU port already in use") pcu.add_node(node, port) diff --git a/PLC/Methods/AddPCU.py b/PLC/Methods/AddPCU.py index 9937c70d..63dd3951 100644 --- a/PLC/Methods/AddPCU.py +++ b/PLC/Methods/AddPCU.py @@ -5,7 +5,7 @@ from PLC.PCUs import PCU, PCUs from PLC.Auth import Auth from PLC.Sites import Site, Sites -can_update = lambda (field, value): field in \ +can_update = lambda field_value: field_value[0] in \ ['ip', 'hostname', 'protocol', 'username', 'password', 'model', 'notes'] @@ -23,7 +23,7 @@ class AddPCU(Method): roles = ['admin', 'pi', 'tech'] - pcu_fields = dict(filter(can_update, PCU.fields.items())) + pcu_fields = dict(list(filter(can_update, list(PCU.fields.items())))) accepts = [ Auth(), @@ -36,17 +36,17 @@ class AddPCU(Method): def call(self, auth, site_id_or_login_base, pcu_fields): - pcu_fields = dict(filter(can_update, pcu_fields.items())) + pcu_fields = dict(list(filter(can_update, list(pcu_fields.items())))) # Get associated site details sites = Sites(self.api, [site_id_or_login_base]) if not sites: - raise PLCInvalidArgument, "No such site" + raise PLCInvalidArgument("No such site") site = sites[0] if 'admin' not in self.caller['roles']: if site['site_id'] not in self.caller['site_ids']: - raise PLCPermissionDenied, "Not allowed to add a PCU to that site" + raise PLCPermissionDenied("Not allowed to add a PCU to that site") pcu = PCU(self.api, pcu_fields) pcu['site_id'] = site['site_id'] diff --git a/PLC/Methods/AddPCUProtocolType.py b/PLC/Methods/AddPCUProtocolType.py index 870144e8..0a9a835d 100644 --- a/PLC/Methods/AddPCUProtocolType.py +++ b/PLC/Methods/AddPCUProtocolType.py @@ -5,7 +5,7 @@ from PLC.PCUProtocolTypes import PCUProtocolType, PCUProtocolTypes from PLC.PCUTypes import PCUType, PCUTypes from PLC.Auth import Auth -can_update = lambda (field, value): field in \ +can_update = lambda field_value: field_value[0] in \ ['pcu_type_id', 'port', 'protocol', 'supported'] class AddPCUProtocolType(Method): @@ -17,7 +17,7 @@ class AddPCUProtocolType(Method): roles = ['admin'] - protocol_type_fields = dict(filter(can_update, PCUProtocolType.fields.items())) + protocol_type_fields = dict(list(filter(can_update, list(PCUProtocolType.fields.items())))) accepts = [ Auth(), @@ -33,20 +33,20 @@ class AddPCUProtocolType(Method): # Check if pcu type exists pcu_types = PCUTypes(self.api, [pcu_type_id_or_model]) if not pcu_types: - raise PLCInvalidArgument, "No such pcu type" + raise PLCInvalidArgument("No such pcu type") pcu_type = pcu_types[0] # Check if this port is already used if 'port' not in protocol_type_fields: - raise PLCInvalidArgument, "Must specify a port" + raise PLCInvalidArgument("Must specify a port") else: protocol_types = PCUProtocolTypes(self.api, {'pcu_type_id': pcu_type['pcu_type_id']}) for protocol_type in protocol_types: if protocol_type['port'] == protocol_type_fields['port']: - raise PLCInvalidArgument, "Port alreay in use" + raise PLCInvalidArgument("Port alreay in use") - protocol_type_fields = dict(filter(can_update, protocol_type_fields.items())) + protocol_type_fields = dict(list(filter(can_update, list(protocol_type_fields.items())))) protocol_type = PCUProtocolType(self.api, protocol_type_fields) protocol_type['pcu_type_id'] = pcu_type['pcu_type_id'] protocol_type.sync() diff --git a/PLC/Methods/AddPCUType.py b/PLC/Methods/AddPCUType.py index 2c8fbe54..4b4bf65b 100644 --- a/PLC/Methods/AddPCUType.py +++ b/PLC/Methods/AddPCUType.py @@ -4,7 +4,7 @@ from PLC.Parameter import Parameter, Mixed from PLC.PCUTypes import PCUType, PCUTypes from PLC.Auth import Auth -can_update = lambda (field, value): field in \ +can_update = lambda field_value: field_value[0] in \ ['model', 'name'] class AddPCUType(Method): @@ -16,7 +16,7 @@ class AddPCUType(Method): roles = ['admin'] - pcu_type_fields = dict(filter(can_update, PCUType.fields.items())) + pcu_type_fields = dict(list(filter(can_update, list(PCUType.fields.items())))) accepts = [ Auth(), @@ -27,7 +27,7 @@ class AddPCUType(Method): def call(self, auth, pcu_type_fields): - pcu_type_fields = dict(filter(can_update, pcu_type_fields.items())) + pcu_type_fields = dict(list(filter(can_update, list(pcu_type_fields.items())))) pcu_type = PCUType(self.api, pcu_type_fields) pcu_type.sync() self.event_object = {'PCUType': [pcu_type['pcu_type_id']]} diff --git a/PLC/Methods/AddPeer.py b/PLC/Methods/AddPeer.py index 868ce11b..f14b845f 100644 --- a/PLC/Methods/AddPeer.py +++ b/PLC/Methods/AddPeer.py @@ -7,7 +7,7 @@ from PLC.Parameter import Parameter, Mixed from PLC.Auth import Auth from PLC.Peers import Peer, Peers -can_update = lambda (field, value): field in \ +can_update = lambda field_value: field_value[0] in \ ['peername', 'peer_url', 'key', 'cacert', 'shortname', 'hrn_root'] class AddPeer(Method): @@ -19,7 +19,7 @@ class AddPeer(Method): roles = ['admin'] - peer_fields = dict(filter(can_update, Peer.fields.items())) + peer_fields = dict(list(filter(can_update, list(Peer.fields.items())))) accepts = [ Auth(), diff --git a/PLC/Methods/AddPerson.py b/PLC/Methods/AddPerson.py index 4ced974f..44208714 100644 --- a/PLC/Methods/AddPerson.py +++ b/PLC/Methods/AddPerson.py @@ -46,11 +46,11 @@ class AddPerson(Method): # type checking native = Row.check_fields(native, self.accepted_fields) if rejected: - raise PLCInvalidArgument, "Cannot add Person with column(s) %r"%rejected + raise PLCInvalidArgument("Cannot add Person with column(s) %r"%rejected) missing=[ r for r in required if r not in native ] if missing: - raise PLCInvalidArgument, "Missing mandatory arguments %s to AddPerson"%missing + raise PLCInvalidArgument("Missing mandatory arguments %s to AddPerson"%missing) # handle native fields native['enabled'] = False @@ -58,11 +58,11 @@ class AddPerson(Method): person.sync() # handle tags - for (tagname,value) in tags.iteritems(): + for (tagname,value) in tags.items(): # the tagtype instance is assumed to exist, just check that tag_types = TagTypes(self.api,{'tagname':tagname}) if not tag_types: - raise PLCInvalidArgument,"No such TagType %s"%tagname + raise PLCInvalidArgument("No such TagType %s"%tagname) tag_type = tag_types[0] person_tags=PersonTags(self.api,{'tagname':tagname,'person_id':person['person_id']}) if not person_tags: diff --git a/PLC/Methods/AddPersonKey.py b/PLC/Methods/AddPersonKey.py index af701859..5c28b773 100644 --- a/PLC/Methods/AddPersonKey.py +++ b/PLC/Methods/AddPersonKey.py @@ -5,7 +5,7 @@ from PLC.Keys import Key, Keys from PLC.Persons import Person, Persons from PLC.Auth import Auth -can_update = lambda (field, value): field in ['key_type','key'] +can_update = lambda field_value: field_value[0] in ['key_type','key'] class AddPersonKey(Method): """ @@ -18,7 +18,7 @@ class AddPersonKey(Method): roles = ['admin', 'pi', 'tech', 'user'] - key_fields = dict(filter(can_update, Key.fields.items())) + key_fields = dict(list(filter(can_update, list(Key.fields.items())))) accepts = [ Auth(), @@ -30,21 +30,21 @@ class AddPersonKey(Method): returns = Parameter(int, 'New key_id (> 0) if successful') def call(self, auth, person_id_or_email, key_fields): - key_fields = dict(filter(can_update, key_fields.items())) + key_fields = dict(list(filter(can_update, list(key_fields.items())))) # Get account details persons = Persons(self.api, [person_id_or_email]) if not persons: - raise PLCInvalidArgument, "No such account" + raise PLCInvalidArgument("No such account") person = persons[0] if person['peer_id'] is not None: - raise PLCInvalidArgument, "Not a local account" + raise PLCInvalidArgument("Not a local account") # If we are not admin, make sure caller is adding a key to their account if 'admin' not in self.caller['roles']: if person['person_id'] != self.caller['person_id']: - raise PLCPermissionDenied, "You may only modify your own keys" + raise PLCPermissionDenied("You may only modify your own keys") key = Key(self.api, key_fields) key.sync(commit = False) diff --git a/PLC/Methods/AddPersonTag.py b/PLC/Methods/AddPersonTag.py index 244b546a..3a438939 100644 --- a/PLC/Methods/AddPersonTag.py +++ b/PLC/Methods/AddPersonTag.py @@ -40,12 +40,12 @@ class AddPersonTag(Method): def call(self, auth, person_id, tag_type_id_or_name, value): persons = Persons(self.api, [person_id]) if not persons: - raise PLCInvalidArgument, "No such person %r"%person_id + raise PLCInvalidArgument("No such person %r"%person_id) person = persons[0] tag_types = TagTypes(self.api, [tag_type_id_or_name]) if not tag_types: - raise PLCInvalidArgument, "No such tag type %r"%tag_type_id_or_name + raise PLCInvalidArgument("No such tag type %r"%tag_type_id_or_name) tag_type = tag_types[0] # checks for existence - does not allow several different settings @@ -53,8 +53,8 @@ class AddPersonTag(Method): 'tag_type_id':tag_type['tag_type_id']}) if len(conflicts) : - raise PLCInvalidArgument, "Person %d (%s) already has setting %d"% \ - (person['person_id'],person['email'], tag_type['tag_type_id']) + raise PLCInvalidArgument("Person %d (%s) already has setting %d"% \ + (person['person_id'],person['email'], tag_type['tag_type_id'])) # check authorizations person.caller_may_write_tag (self.api,self.caller,tag_type) diff --git a/PLC/Methods/AddPersonToSite.py b/PLC/Methods/AddPersonToSite.py index 9710f2ba..0e0f6a39 100644 --- a/PLC/Methods/AddPersonToSite.py +++ b/PLC/Methods/AddPersonToSite.py @@ -35,20 +35,20 @@ class AddPersonToSite(Method): # Get account information persons = Persons(self.api, [person_id_or_email]) if not persons: - raise PLCInvalidArgument, "No such account" + raise PLCInvalidArgument("No such account") person = persons[0] if person['peer_id'] is not None: - raise PLCInvalidArgument, "Not a local account" + raise PLCInvalidArgument("Not a local account") # Get site information sites = Sites(self.api, [site_id_or_login_base]) if not sites: - raise PLCInvalidArgument, "No such site" + raise PLCInvalidArgument("No such site") site = sites[0] if site['peer_id'] is not None: - raise PLCInvalidArgument, "Not a local site" + raise PLCInvalidArgument("Not a local site") if site['site_id'] not in person['site_ids']: site.add_person(person) diff --git a/PLC/Methods/AddPersonToSlice.py b/PLC/Methods/AddPersonToSlice.py index 41e6a6a1..172e4286 100644 --- a/PLC/Methods/AddPersonToSlice.py +++ b/PLC/Methods/AddPersonToSlice.py @@ -29,26 +29,26 @@ class AddPersonToSlice(Method): # Get account information persons = Persons(self.api, [person_id_or_email]) if not persons: - raise PLCInvalidArgument, "No such account %s"%person_id_or_email + raise PLCInvalidArgument("No such account %s"%person_id_or_email) person = persons[0] # Get slice information slices = Slices(self.api, [slice_id_or_name]) if not slices: - raise PLCInvalidArgument, "No such slice %s"%slice_id_or_name + raise PLCInvalidArgument("No such slice %s"%slice_id_or_name) slice = slices[0] # N.B. Allow foreign users to be added to local slices and # local users to be added to foreign slices (and, of course, # local users to be added to local slices). if person['peer_id'] is not None and slice['peer_id'] is not None: - raise PLCInvalidArgument, "Cannot add foreign users to foreign slices" + raise PLCInvalidArgument("Cannot add foreign users to foreign slices") # If we are not admin, make sure the caller is a PI # of the site associated with the slice if 'admin' not in self.caller['roles']: if slice['site_id'] not in self.caller['site_ids']: - raise PLCPermissionDenied, "Not allowed to add users to slice %s"%slice_id_or_name + raise PLCPermissionDenied("Not allowed to add users to slice %s"%slice_id_or_name) if slice['slice_id'] not in person['slice_ids']: slice.add_person(person) diff --git a/PLC/Methods/AddRoleToPerson.py b/PLC/Methods/AddRoleToPerson.py index 1e47033d..4f275af8 100644 --- a/PLC/Methods/AddRoleToPerson.py +++ b/PLC/Methods/AddRoleToPerson.py @@ -31,29 +31,29 @@ class AddRoleToPerson(Method): # Get role roles = Roles(self.api, [role_id_or_name]) if not roles: - raise PLCInvalidArgument, "Invalid role '%s'" % unicode(role_id_or_name) + raise PLCInvalidArgument("Invalid role '%s'" % str(role_id_or_name)) role = roles[0] # Get account information persons = Persons(self.api, [person_id_or_email]) if not persons: - raise PLCInvalidArgument, "No such account" + raise PLCInvalidArgument("No such account") person = persons[0] if person['peer_id'] is not None: - raise PLCInvalidArgument, "Not a local account" + raise PLCInvalidArgument("Not a local account") # Authenticated function assert self.caller is not None # Check if we can update this account if not self.caller.can_update(person): - raise PLCPermissionDenied, "Not allowed to update specified account" + raise PLCPermissionDenied("Not allowed to update specified account") # Can only grant lesser (higher) roles to others if 'admin' not in self.caller['roles'] and \ role['role_id'] <= min(self.caller['role_ids']): - raise PLCInvalidArgument, "Not allowed to grant that role" + raise PLCInvalidArgument("Not allowed to grant that role") if role['role_id'] not in person['role_ids']: person.add_role(role) diff --git a/PLC/Methods/AddRoleToTagType.py b/PLC/Methods/AddRoleToTagType.py index 947adcdf..cb2e9f2e 100644 --- a/PLC/Methods/AddRoleToTagType.py +++ b/PLC/Methods/AddRoleToTagType.py @@ -31,13 +31,13 @@ class AddRoleToTagType(Method): # Get role roles = Roles(self.api, [role_id_or_name]) if not roles: - raise PLCInvalidArgument, "Invalid role '%s'" % unicode(role_id_or_name) + raise PLCInvalidArgument("Invalid role '%s'" % str(role_id_or_name)) role = roles[0] # Get subject tag type tag_types = TagTypes(self.api, [tag_type_id_or_tagname]) if not tag_types: - raise PLCInvalidArgument, "No such tag type" + raise PLCInvalidArgument("No such tag type") tag_type = tag_types[0] # Authenticated function @@ -45,7 +45,7 @@ class AddRoleToTagType(Method): # Only admins if 'admin' not in self.caller['roles']: - raise PLCInvalidArgument, "Not allowed to grant that role" + raise PLCInvalidArgument("Not allowed to grant that role") if role['role_id'] not in tag_type['role_ids']: tag_type.add_role(role) diff --git a/PLC/Methods/AddSession.py b/PLC/Methods/AddSession.py index 32da2019..759bc3be 100644 --- a/PLC/Methods/AddSession.py +++ b/PLC/Methods/AddSession.py @@ -26,7 +26,7 @@ class AddSession(Method): persons = Persons(self.api, [person_id_or_email], ['person_id', 'email']) if not persons: - raise PLCInvalidArgument, "No such person" + raise PLCInvalidArgument("No such person") person = persons[0] session = Session(self.api) diff --git a/PLC/Methods/AddSite.py b/PLC/Methods/AddSite.py index 2150a912..5f1a957a 100644 --- a/PLC/Methods/AddSite.py +++ b/PLC/Methods/AddSite.py @@ -6,7 +6,7 @@ from PLC.Auth import Auth from PLC.Methods.AddSiteTag import AddSiteTag -can_update = lambda (field, value): field in \ +can_update = lambda field_value: field_value[0] in \ ['name', 'abbreviated_name', 'login_base', 'is_public', 'latitude', 'longitude', 'url', 'max_slices', 'max_slivers', 'enabled', 'ext_consortium_id'] @@ -22,7 +22,7 @@ class AddSite(Method): roles = ['admin'] - site_fields = dict(filter(can_update, Site.fields.items())) + site_fields = dict(list(filter(can_update, list(Site.fields.items())))) accepts = [ Auth(), @@ -32,7 +32,7 @@ class AddSite(Method): returns = Parameter(int, 'New site_id (> 0) if successful') def call(self, auth, site_fields): - site_fields = dict(filter(can_update, site_fields.items())) + site_fields = dict(list(filter(can_update, list(site_fields.items())))) site = Site(self.api, site_fields) site.sync() diff --git a/PLC/Methods/AddSiteAddress.py b/PLC/Methods/AddSiteAddress.py index 55148054..7a467e5b 100644 --- a/PLC/Methods/AddSiteAddress.py +++ b/PLC/Methods/AddSiteAddress.py @@ -5,7 +5,7 @@ from PLC.Addresses import Address, Addresses from PLC.Auth import Auth from PLC.Sites import Site, Sites -can_update = lambda (field, value): field in \ +can_update = lambda field_value: field_value[0] in \ ['line1', 'line2', 'line3', 'city', 'state', 'postalcode', 'country'] @@ -21,7 +21,7 @@ class AddSiteAddress(Method): roles = ['admin', 'pi'] - address_fields = dict(filter(can_update, Address.fields.items())) + address_fields = dict(list(filter(can_update, list(Address.fields.items())))) accepts = [ Auth(), @@ -33,17 +33,17 @@ class AddSiteAddress(Method): returns = Parameter(int, 'New address_id (> 0) if successful') def call(self, auth, site_id_or_login_base, address_fields): - address_fields = dict(filter(can_update, address_fields.items())) + address_fields = dict(list(filter(can_update, list(address_fields.items())))) # Get associated site details sites = Sites(self.api, [site_id_or_login_base]) if not sites: - raise PLCInvalidArgument, "No such site" + raise PLCInvalidArgument("No such site") site = sites[0] if 'admin' not in self.caller['roles']: if site['site_id'] not in self.caller['site_ids']: - raise PLCPermissionDenied, "Address must be associated with one of your sites" + raise PLCPermissionDenied("Address must be associated with one of your sites") address = Address(self.api, address_fields) address.sync(commit = False) diff --git a/PLC/Methods/AddSiteTag.py b/PLC/Methods/AddSiteTag.py index bb5cfaeb..0e7561bb 100644 --- a/PLC/Methods/AddSiteTag.py +++ b/PLC/Methods/AddSiteTag.py @@ -43,12 +43,12 @@ class AddSiteTag(Method): def call(self, auth, site_id, tag_type_id_or_name, value): sites = Sites(self.api, [site_id]) if not sites: - raise PLCInvalidArgument, "No such site %r"%site_id + raise PLCInvalidArgument("No such site %r"%site_id) site = sites[0] tag_types = TagTypes(self.api, [tag_type_id_or_name]) if not tag_types: - raise PLCInvalidArgument, "No such tag type %r"%tag_type_id_or_name + raise PLCInvalidArgument("No such tag type %r"%tag_type_id_or_name) tag_type = tag_types[0] # checks for existence - does not allow several different settings @@ -57,8 +57,8 @@ class AddSiteTag(Method): 'tag_type_id':tag_type['tag_type_id']}) if len(conflicts) : - raise PLCInvalidArgument, "Site %d already has setting %d"%(site['site_id'], - tag_type['tag_type_id']) + raise PLCInvalidArgument("Site %d already has setting %d"%(site['site_id'], + tag_type['tag_type_id'])) # check authorizations site.caller_may_write_tag(self.api,self.caller,tag_type) diff --git a/PLC/Methods/AddSlice.py b/PLC/Methods/AddSlice.py index 7542cf07..da1057e5 100644 --- a/PLC/Methods/AddSlice.py +++ b/PLC/Methods/AddSlice.py @@ -53,7 +53,7 @@ class AddSlice(Method): # type checking native = Row.check_fields (native, self.accepted_fields) if rejected: - raise PLCInvalidArgument, "Cannot add Slice with column(s) %r"%rejected + raise PLCInvalidArgument("Cannot add Slice with column(s) %r"%rejected) # Authenticated function assert self.caller is not None @@ -66,26 +66,25 @@ class AddSlice(Method): good_name = r'^[a-z0-9\.]+_[a-zA-Z0-9_\.]+$' if not name or \ not re.match(good_name, name): - raise PLCInvalidArgument, "Invalid slice name" + raise PLCInvalidArgument("Invalid slice name") # Get associated site details login_base = name.split("_")[0] sites = Sites(self.api, [login_base]) if not sites: - raise PLCInvalidArgument, "Invalid slice prefix %s in %s"%(login_base,name) + raise PLCInvalidArgument("Invalid slice prefix %s in %s"%(login_base,name)) site = sites[0] if 'admin' not in self.caller['roles']: if site['site_id'] not in self.caller['site_ids']: - raise PLCPermissionDenied, "Slice prefix %s must match one of your sites' login_base"%login_base + raise PLCPermissionDenied("Slice prefix %s must match one of your sites' login_base"%login_base) if len(site['slice_ids']) >= site['max_slices']: - raise PLCInvalidArgument, \ - "Site %s has reached (%d) its maximum allowable slice count (%d)"%(site['name'], + raise PLCInvalidArgument("Site %s has reached (%d) its maximum allowable slice count (%d)"%(site['name'], len(site['slice_ids']), - site['max_slices']) + site['max_slices'])) if not site['enabled']: - raise PLCInvalidArgument, "Site %s is disabled and can cannot create slices" % (site['name']) + raise PLCInvalidArgument("Site %s is disabled and can cannot create slices" % (site['name'])) slice = Slice(self.api, native) slice['creator_person_id'] = self.caller['person_id'] @@ -96,10 +95,10 @@ class AddSlice(Method): root_auth = self.api.config.PLC_HRN_ROOT tags['hrn'] = '.'.join([root_auth, login_base, name.split("_")[1]]) - for (tagname,value) in tags.iteritems(): + for (tagname,value) in tags.items(): # the tagtype instance is assumed to exist, just check that if not TagTypes(self.api,{'tagname':tagname}): - raise PLCInvalidArgument,"No such TagType %s"%tagname + raise PLCInvalidArgument("No such TagType %s"%tagname) slice_tags=SliceTags(self.api,{'tagname':tagname,'slice_id':slice['slice_id']}) if not slice_tags: AddSliceTag(self.api).__call__(auth,slice['slice_id'],tagname,value) diff --git a/PLC/Methods/AddSliceTag.py b/PLC/Methods/AddSliceTag.py index ef78fa68..2ca54785 100644 --- a/PLC/Methods/AddSliceTag.py +++ b/PLC/Methods/AddSliceTag.py @@ -56,12 +56,12 @@ class AddSliceTag(Method): def call(self, auth, slice_id_or_name, tag_type_id_or_name, value, node_id_or_hostname = None, nodegroup_id_or_name = None): slices = Slices(self.api, [slice_id_or_name]) if not slices: - raise PLCInvalidArgument, "No such slice %r"%slice_id_or_name + raise PLCInvalidArgument("No such slice %r"%slice_id_or_name) slice = slices[0] tag_types = TagTypes(self.api, [tag_type_id_or_name]) if not tag_types: - raise PLCInvalidArgument, "No such tag type %r"%tag_type_id_or_name + raise PLCInvalidArgument("No such tag type %r"%tag_type_id_or_name) tag_type = tag_types[0] # check authorizations @@ -71,12 +71,12 @@ class AddSliceTag(Method): if tag_type['tagname'] in ['initscript']: initscripts = InitScripts(self.api, {'enabled': True, 'name': value}) if not initscripts: - raise PLCInvalidArgument, "No such plc initscript %r"%value + raise PLCInvalidArgument("No such plc initscript %r"%value) slice_tag = SliceTag(self.api) slice_tag['slice_id'] = slice['slice_id'] slice_tag['tag_type_id'] = tag_type['tag_type_id'] - slice_tag['value'] = unicode(value) + slice_tag['value'] = str(value) # Sliver attribute if node is specified if node_id_or_hostname is not None or isinstance(self.caller, Node): @@ -88,28 +88,28 @@ class AddSliceTag(Method): if node_id_or_hostname is not None: nodes = Nodes(self.api, [node_id_or_hostname]) if not nodes: - raise PLCInvalidArgument, "No such node" + raise PLCInvalidArgument("No such node") node = nodes[0] - if node_id <> None and node_id <> node['node_id']: - raise PLCPermissionDenied, "Not allowed to set another node's sliver attribute" + if node_id != None and node_id != node['node_id']: + raise PLCPermissionDenied("Not allowed to set another node's sliver attribute") else: node_id = node['node_id'] system_slice_tags = SliceTags(self.api, {'tagname': 'system', 'value': '1'}).dict('slice_id') - system_slice_ids = system_slice_tags.keys() + system_slice_ids = list(system_slice_tags.keys()) if slice['slice_id'] not in system_slice_ids and node_id not in slice['node_ids']: - raise PLCInvalidArgument, "AddSliceTag: slice %s not on specified node %s nor is it a system slice (%r)"%\ - (slice['name'],node['hostname'],system_slice_ids) + raise PLCInvalidArgument("AddSliceTag: slice %s not on specified node %s nor is it a system slice (%r)"%\ + (slice['name'],node['hostname'],system_slice_ids)) slice_tag['node_id'] = node['node_id'] # Sliver attribute shared accross nodes if nodegroup is sepcified if nodegroup_id_or_name is not None: if isinstance(self.caller, Node): - raise PLCPermissionDenied, "Not allowed to set nodegroup slice attributes" + raise PLCPermissionDenied("Not allowed to set nodegroup slice attributes") nodegroups = NodeGroups(self.api, [nodegroup_id_or_name]) if not nodegroups: - raise PLCInvalidArgument, "No such nodegroup %r"%nodegroup_id_or_name + raise PLCInvalidArgument("No such nodegroup %r"%nodegroup_id_or_name) nodegroup = nodegroups[0] slice_tag['nodegroup_id'] = nodegroup['nodegroup_id'] @@ -126,11 +126,11 @@ class AddSliceTag(Method): if 'node_id' in slice_tag and slice_tag['node_id'] is not None and slice_tag_check['node_id'] is None: continue if 'node_id' in slice_tag and slice_tag['node_id'] == slice_tag_check['node_id']: - raise PLCInvalidArgument, "Sliver attribute already exists" + raise PLCInvalidArgument("Sliver attribute already exists") if 'nodegroup_id' in slice_tag and slice_tag['nodegroup_id'] == slice_tag_check['nodegroup_id']: - raise PLCInvalidArgument, "Slice attribute already exists for this nodegroup" + raise PLCInvalidArgument("Slice attribute already exists for this nodegroup") if node_id_or_hostname is None and nodegroup_id_or_name is None: - raise PLCInvalidArgument, "Slice attribute already exists" + raise PLCInvalidArgument("Slice attribute already exists") slice_tag.sync() self.event_objects = {'SliceTag': [slice_tag['slice_tag_id']]} diff --git a/PLC/Methods/AddSliceToNodes.py b/PLC/Methods/AddSliceToNodes.py index db074caf..b0bd880b 100644 --- a/PLC/Methods/AddSliceToNodes.py +++ b/PLC/Methods/AddSliceToNodes.py @@ -33,19 +33,19 @@ class AddSliceToNodes(Method): # Get slice information slices = Slices(self.api, [slice_id_or_name]) if not slices: - raise PLCInvalidArgument, "No such slice %r"%slice_id_or_name + raise PLCInvalidArgument("No such slice %r"%slice_id_or_name) slice = slices[0] if slice['peer_id'] is not None: - raise PLCInvalidArgument, "Not a local slice" + raise PLCInvalidArgument("Not a local slice") if 'admin' not in self.caller['roles']: if self.caller['person_id'] in slice['person_ids']: pass elif 'pi' not in self.caller['roles']: - raise PLCPermissionDenied, "Not a member of the specified slice" + raise PLCPermissionDenied("Not a member of the specified slice") elif slice['site_id'] not in self.caller['site_ids']: - raise PLCPermissionDenied, "Specified slice not associated with any of your sites" + raise PLCPermissionDenied("Specified slice not associated with any of your sites") # Get specified nodes, add them to the slice nodes = Nodes(self.api, node_id_or_hostname_list, @@ -57,8 +57,8 @@ class AddSliceToNodes(Method): if node['slice_ids_whitelist'] and \ slice['slice_id'] not in node['slice_ids_whitelist'] and \ not set(self.caller['site_ids']).intersection([node['site_id']]): - raise PLCInvalidArgument, "%s is not allowed on %s (not on the whitelist)" % \ - (slice['name'], node['hostname']) + raise PLCInvalidArgument("%s is not allowed on %s (not on the whitelist)" % \ + (slice['name'], node['hostname'])) if slice['slice_id'] not in node['slice_ids']: slice.add_node(node, commit = False) diff --git a/PLC/Methods/AddSliceToNodesWhitelist.py b/PLC/Methods/AddSliceToNodesWhitelist.py index 4dde439a..9afc6949 100644 --- a/PLC/Methods/AddSliceToNodesWhitelist.py +++ b/PLC/Methods/AddSliceToNodesWhitelist.py @@ -32,17 +32,17 @@ class AddSliceToNodesWhitelist(Method): # Get slice information slices = Slices(self.api, [slice_id_or_name]) if not slices: - raise PLCInvalidArgument, "No such slice" + raise PLCInvalidArgument("No such slice") slice = slices[0] if slice['peer_id'] is not None: - raise PLCInvalidArgument, "Not a local slice" + raise PLCInvalidArgument("Not a local slice") # Get specified nodes, add them to the slice nodes = Nodes(self.api, node_id_or_hostname_list) for node in nodes: if node['peer_id'] is not None: - raise PLCInvalidArgument, "%s not a local node" % node['hostname'] + raise PLCInvalidArgument("%s not a local node" % node['hostname']) if slice['slice_id'] not in node['slice_ids_whitelist']: slice.add_to_node_whitelist(node, commit = False) diff --git a/PLC/Methods/AddTagType.py b/PLC/Methods/AddTagType.py index 6432e056..cec8ba55 100644 --- a/PLC/Methods/AddTagType.py +++ b/PLC/Methods/AddTagType.py @@ -8,7 +8,7 @@ from PLC.Parameter import Parameter, Mixed from PLC.TagTypes import TagType, TagTypes from PLC.Auth import Auth -can_update = lambda (field, value): field in \ +can_update = lambda field_value: field_value[0] in \ ['tagname', 'description', 'category'] class AddTagType(Method): @@ -22,7 +22,7 @@ class AddTagType(Method): roles = ['admin'] - tag_type_fields = dict(filter(can_update, TagType.fields.items())) + tag_type_fields = dict(list(filter(can_update, list(TagType.fields.items())))) accepts = [ Auth(), @@ -33,7 +33,7 @@ class AddTagType(Method): def call(self, auth, tag_type_fields): - tag_type_fields = dict(filter(can_update, tag_type_fields.items())) + tag_type_fields = dict(list(filter(can_update, list(tag_type_fields.items())))) tag_type = TagType(self.api, tag_type_fields) tag_type.sync() diff --git a/PLC/Methods/BindObjectToPeer.py b/PLC/Methods/BindObjectToPeer.py index ea16536d..a6848099 100644 --- a/PLC/Methods/BindObjectToPeer.py +++ b/PLC/Methods/BindObjectToPeer.py @@ -43,8 +43,8 @@ class BindObjectToPeer(Method): # invoke e.g. Nodes ({'node_id':node_id}) objs=class_obj(self.api,{id_name:object_id}) if len(objs) != 1: - raise PLCInvalidArgument,"Cannot locate object, type=%s id=%d"%\ - (type,object_id) + raise PLCInvalidArgument("Cannot locate object, type=%s id=%d"%\ + (type,object_id)) return objs[0] @@ -52,11 +52,11 @@ class BindObjectToPeer(Method): object_type = object_type.lower() if object_type not in self.known_types: - raise PLCInvalidArgument, 'Unrecognized object type %s'%object_type + raise PLCInvalidArgument('Unrecognized object type %s'%object_type) peers=Peers(self.api,{'shortname':shortname.upper()}) if len(peers) !=1: - raise PLCInvalidArgument, 'No such peer with shortname %s'%shortname + raise PLCInvalidArgument('No such peer with shortname %s'%shortname) peer=peers[0] object = self.locate_object (object_type, object_id) diff --git a/PLC/Methods/BlacklistKey.py b/PLC/Methods/BlacklistKey.py index 2afd664c..86721e91 100644 --- a/PLC/Methods/BlacklistKey.py +++ b/PLC/Methods/BlacklistKey.py @@ -28,7 +28,7 @@ class BlacklistKey(Method): # Get associated key details keys = Keys(self.api, [key_id]) if not keys: - raise PLCInvalidArgument, "No such key" + raise PLCInvalidArgument("No such key") key = keys[0] # N.B.: Can blacklist any key, even foreign ones diff --git a/PLC/Methods/BootGetNodeDetails.py b/PLC/Methods/BootGetNodeDetails.py index afc7b0c7..1009dcb0 100644 --- a/PLC/Methods/BootGetNodeDetails.py +++ b/PLC/Methods/BootGetNodeDetails.py @@ -44,7 +44,7 @@ class BootGetNodeDetails(Method): for network in details['networks']: for field in network: if network[field] is None: - if isinstance(network[field], (int, long)): + if isinstance(network[field], int): network[field] = -1 else: network[field] = "" diff --git a/PLC/Methods/BootUpdateNode.py b/PLC/Methods/BootUpdateNode.py index d7c85b3f..5606ee80 100644 --- a/PLC/Methods/BootUpdateNode.py +++ b/PLC/Methods/BootUpdateNode.py @@ -8,7 +8,7 @@ from PLC.Nodes import Node, Nodes from PLC.Interfaces import Interface, Interfaces from PLC.Timestamp import * -can_update = lambda (field, value): field in \ +can_update = lambda field_value: field_value[0] in \ ['method', 'mac', 'gateway', 'network', 'broadcast', 'netmask', 'dns1', 'dns2'] @@ -22,7 +22,7 @@ class BootUpdateNode(Method): roles = ['node'] - interface_fields = dict(filter(can_update, Interface.fields.items())) + interface_fields = dict(list(filter(can_update, list(Interface.fields.items())))) accepts = [ Mixed(BootAuth(), SessionAuth()), @@ -39,7 +39,7 @@ class BootUpdateNode(Method): def call(self, auth, node_fields): if not isinstance(self.caller, Node): - raise PLCInvalidArgument,"Caller is expected to be a node" + raise PLCInvalidArgument("Caller is expected to be a node") node = self.caller @@ -47,35 +47,35 @@ class BootUpdateNode(Method): # otherwise the db gets spammed with meaningless entries changed_fields = [] # Update node state - if node_fields.has_key('boot_state'): + if 'boot_state' in node_fields: if node['boot_state'] != node_fields['boot_state']: changed_fields.append('boot_state') node['boot_state'] = node_fields['boot_state'] ### for legacy BootManager - if node_fields.has_key('ssh_host_key'): + if 'ssh_host_key' in node_fields: if node['ssh_rsa_key'] != node_fields['ssh_host_key']: changed_fields.append('ssh_rsa_key') node['ssh_rsa_key'] = node_fields['ssh_host_key'] - if node_fields.has_key('ssh_rsa_key'): + if 'ssh_rsa_key' in node_fields: if node['ssh_rsa_key'] != node_fields['ssh_rsa_key']: changed_fields.append('ssh_rsa_key') node['ssh_rsa_key'] = node_fields['ssh_rsa_key'] # Update primary interface state - if node_fields.has_key('primary_network'): + if 'primary_network' in node_fields: primary_network = node_fields['primary_network'] if 'interface_id' not in primary_network: - raise PLCInvalidArgument, "Interface not specified" + raise PLCInvalidArgument("Interface not specified") if primary_network['interface_id'] not in node['interface_ids']: - raise PLCInvalidArgument, "Interface not associated with calling node" + raise PLCInvalidArgument("Interface not associated with calling node") interfaces = Interfaces(self.api, [primary_network['interface_id']]) if not interfaces: - raise PLCInvalidArgument, "No such interface %r"%interface_id + raise PLCInvalidArgument("No such interface %r"%interface_id) interface = interfaces[0] if not interface['is_primary']: - raise PLCInvalidArgument, "Not the primary interface on record" + raise PLCInvalidArgument("Not the primary interface on record") - interface_fields = dict(filter(can_update, primary_network.items())) + interface_fields = dict(list(filter(can_update, list(primary_network.items())))) for field in interface_fields: if interface[field] != primary_network[field] : changed_fields.append('Interface.'+field) interface.update(interface_fields) @@ -84,7 +84,7 @@ class BootUpdateNode(Method): current_time = int(time.time()) # ONLY UPDATE ONCE when the boot_state flag and ssh_rsa_key flag are NOT passed - if not node_fields.has_key('boot_state') and not node_fields.has_key('ssh_rsa_key'): + if 'boot_state' not in node_fields and 'ssh_rsa_key' not in node_fields: # record times spent on and off line by comparing last_contact with previous value of last_boot if node['last_boot'] and node['last_contact']: diff --git a/PLC/Methods/DeleteAddress.py b/PLC/Methods/DeleteAddress.py index 406965bb..66f1beab 100644 --- a/PLC/Methods/DeleteAddress.py +++ b/PLC/Methods/DeleteAddress.py @@ -27,12 +27,12 @@ class DeleteAddress(Method): # Get associated address details addresses = Addresses(self.api, address_id) if not addresses: - raise PLCInvalidArgument, "No such address" + raise PLCInvalidArgument("No such address") address = addresses[0] if 'admin' not in self.caller['roles']: if address['site_id'] not in self.caller['site_ids']: - raise PLCPermissionDenied, "Address must be associated with one of your sites" + raise PLCPermissionDenied("Address must be associated with one of your sites") address.delete() diff --git a/PLC/Methods/DeleteAddressType.py b/PLC/Methods/DeleteAddressType.py index ca6cadb8..66340f2c 100644 --- a/PLC/Methods/DeleteAddressType.py +++ b/PLC/Methods/DeleteAddressType.py @@ -25,7 +25,7 @@ class DeleteAddressType(Method): def call(self, auth, address_type_id_or_name): address_types = AddressTypes(self.api, [address_type_id_or_name]) if not address_types: - raise PLCInvalidArgument, "No such address type" + raise PLCInvalidArgument("No such address type") address_type = address_types[0] address_type.delete() self.event_objects = {'AddressType': [address_type['address_type_id']]} diff --git a/PLC/Methods/DeleteAddressTypeFromAddress.py b/PLC/Methods/DeleteAddressTypeFromAddress.py index e12a5dfa..c9b95e49 100644 --- a/PLC/Methods/DeleteAddressTypeFromAddress.py +++ b/PLC/Methods/DeleteAddressTypeFromAddress.py @@ -29,17 +29,17 @@ class DeleteAddressTypeFromAddress(Method): def call(self, auth, address_type_id_or_name, address_id): address_types = AddressTypes(self.api, [address_type_id_or_name]) if not address_types: - raise PLCInvalidArgument, "No such address type" + raise PLCInvalidArgument("No such address type") address_type = address_types[0] addresses = Addresses(self.api, [address_id]) if not addresses: - raise PLCInvalidArgument, "No such address" + raise PLCInvalidArgument("No such address") address = addresses[0] if 'admin' not in self.caller['roles']: if address['site_id'] not in self.caller['site_ids']: - raise PLCPermissionDenied, "Address must be associated with one of your sites" + raise PLCPermissionDenied("Address must be associated with one of your sites") address.remove_address_type(address_type) self.event_objects = {'Address' : [address['address_id']], diff --git a/PLC/Methods/DeleteAllPeerEntries.py b/PLC/Methods/DeleteAllPeerEntries.py index 5499ba84..72ff274b 100644 --- a/PLC/Methods/DeleteAllPeerEntries.py +++ b/PLC/Methods/DeleteAllPeerEntries.py @@ -85,19 +85,19 @@ class DeleteAllPeerEntries(Method): (Site, Sites)): classname = singular.__name__ objs = plural(self.api, {'peer_id': peer_id}) - print("Found {len} {classname}s from peer {peername}" + print(("Found {len} {classname}s from peer {peername}" .format(len=len(objs), classname=classname, - peername=peername)) + peername=peername))) if dry_run: print("dry-run mode: skipping actual deletion") else: - print("Deleting {classname}s".format(classname=classname)) + print(("Deleting {classname}s".format(classname=classname))) for obj in objs: - print '.', + print('.', end=' ') sys.stdout.flush() obj.delete(commit=commit_mode) - print + print() # Update peer itself and commit peer.sync(commit=True) diff --git a/PLC/Methods/DeleteBootState.py b/PLC/Methods/DeleteBootState.py index 1bea3db7..84f24c53 100644 --- a/PLC/Methods/DeleteBootState.py +++ b/PLC/Methods/DeleteBootState.py @@ -27,7 +27,7 @@ class DeleteBootState(Method): def call(self, auth, name): boot_states = BootStates(self.api, [name]) if not boot_states: - raise PLCInvalidArgument, "No such boot state" + raise PLCInvalidArgument("No such boot state") boot_state = boot_states[0] boot_state.delete() diff --git a/PLC/Methods/DeleteConfFile.py b/PLC/Methods/DeleteConfFile.py index 360ccfbe..fb7851d8 100644 --- a/PLC/Methods/DeleteConfFile.py +++ b/PLC/Methods/DeleteConfFile.py @@ -24,7 +24,7 @@ class DeleteConfFile(Method): def call(self, auth, conf_file_id): conf_files = ConfFiles(self.api, [conf_file_id]) if not conf_files: - raise PLCInvalidArgument, "No such configuration file" + raise PLCInvalidArgument("No such configuration file") conf_file = conf_files[0] conf_file.delete() diff --git a/PLC/Methods/DeleteConfFileFromNode.py b/PLC/Methods/DeleteConfFileFromNode.py index 53c808c9..85a0a92e 100644 --- a/PLC/Methods/DeleteConfFileFromNode.py +++ b/PLC/Methods/DeleteConfFileFromNode.py @@ -28,13 +28,13 @@ class DeleteConfFileFromNode(Method): # Get configuration file conf_files = ConfFiles(self.api, [conf_file_id]) if not conf_files: - raise PLCInvalidArgument, "No such configuration file" + raise PLCInvalidArgument("No such configuration file") conf_file = conf_files[0] # Get node nodes = Nodes(self.api, [node_id_or_hostname]) if not nodes: - raise PLCInvalidArgument, "No such node" + raise PLCInvalidArgument("No such node") node = nodes[0] # Link configuration file to node diff --git a/PLC/Methods/DeleteConfFileFromNodeGroup.py b/PLC/Methods/DeleteConfFileFromNodeGroup.py index 243a1a18..96398a94 100644 --- a/PLC/Methods/DeleteConfFileFromNodeGroup.py +++ b/PLC/Methods/DeleteConfFileFromNodeGroup.py @@ -29,13 +29,13 @@ class DeleteConfFileFromNodeGroup(Method): # Get configuration file conf_files = ConfFiles(self.api, [conf_file_id]) if not conf_files: - raise PLCInvalidArgument, "No such configuration file" + raise PLCInvalidArgument("No such configuration file") conf_file = conf_files[0] # Get nodegroup nodegroups = NodeGroups(self.api, [nodegroup_id_or_name]) if not nodegroups: - raise PLCInvalidArgument, "No such nodegroup" + raise PLCInvalidArgument("No such nodegroup") nodegroup = nodegroups[0] # Link configuration file to nodegroup diff --git a/PLC/Methods/DeleteIlink.py b/PLC/Methods/DeleteIlink.py index 0d07dfe3..9bd41bd8 100644 --- a/PLC/Methods/DeleteIlink.py +++ b/PLC/Methods/DeleteIlink.py @@ -41,7 +41,7 @@ class DeleteIlink(Method): def call(self, auth, ilink_id): ilinks = Ilinks(self.api, [ilink_id]) if not ilinks: - raise PLCInvalidArgument, "No such ilink %r"%ilink_id + raise PLCInvalidArgument("No such ilink %r"%ilink_id) ilink = ilinks[0] src_if=Interfaces(self.api,ilink['src_interface_id'])[0] @@ -54,13 +54,13 @@ class DeleteIlink(Method): if 'admin' in self.caller['roles']: pass elif not AuthorizeHelpers.caller_may_access_tag_type (self.api, self.caller, tag_type): - raise PLCPermissionDenied, "%s, forbidden tag %s"%(self.name,tag_type['tagname']) + raise PLCPermissionDenied("%s, forbidden tag %s"%(self.name,tag_type['tagname'])) elif AuthorizeHelpers.interface_belongs_to_person (self.api, src_if, self.caller): pass elif src_if_id != dst_if_id and AuthorizeHelpers.interface_belongs_to_person (self.api, dst_if, self.caller): pass else: - raise PLCPermissionDenied, "%s: you must own either the src or dst interface"%self.name + raise PLCPermissionDenied("%s: you must own either the src or dst interface"%self.name) ilink.delete() self.object_ids = [ilink['src_interface_id'],ilink['dst_interface_id']] diff --git a/PLC/Methods/DeleteInitScript.py b/PLC/Methods/DeleteInitScript.py index 28f6558f..cb315ea2 100644 --- a/PLC/Methods/DeleteInitScript.py +++ b/PLC/Methods/DeleteInitScript.py @@ -25,7 +25,7 @@ class DeleteInitScript(Method): def call(self, auth, initscript_id_or_name): initscripts = InitScripts(self.api, [initscript_id_or_name]) if not initscripts: - raise PLCInvalidArgument, "No such initscript" + raise PLCInvalidArgument("No such initscript") initscript = initscripts[0] initscript.delete() diff --git a/PLC/Methods/DeleteInterface.py b/PLC/Methods/DeleteInterface.py index 229a0d75..2747e46c 100644 --- a/PLC/Methods/DeleteInterface.py +++ b/PLC/Methods/DeleteInterface.py @@ -30,13 +30,13 @@ class DeleteInterface(Method): # Get interface information interfaces = Interfaces(self.api, [interface_id]) if not interfaces: - raise PLCInvalidArgument, "No such interface %r"%interface_id + raise PLCInvalidArgument("No such interface %r"%interface_id) interface = interfaces[0] # Get node information nodes = Nodes(self.api, [interface['node_id']]) if not nodes: - raise PLCInvalidArgument, "No such node %r"%node_id + raise PLCInvalidArgument("No such node %r"%node_id) node = nodes[0] # Authenticated functino @@ -46,7 +46,7 @@ class DeleteInterface(Method): # member of the site at which the node is located. if 'admin' not in self.caller['roles']: if node['site_id'] not in self.caller['site_ids']: - raise PLCPermissionDenied, "Not allowed to delete this interface" + raise PLCPermissionDenied("Not allowed to delete this interface") interface.delete() diff --git a/PLC/Methods/DeleteInterfaceTag.py b/PLC/Methods/DeleteInterfaceTag.py index 5ef9635f..164ba53b 100644 --- a/PLC/Methods/DeleteInterfaceTag.py +++ b/PLC/Methods/DeleteInterfaceTag.py @@ -38,7 +38,7 @@ class DeleteInterfaceTag(Method): def call(self, auth, interface_tag_id): interface_tags = InterfaceTags(self.api, [interface_tag_id]) if not interface_tags: - raise PLCInvalidArgument, "No such interface tag %r"%interface_tag_id + raise PLCInvalidArgument("No such interface tag %r"%interface_tag_id) interface_tag = interface_tags[0] tag_type_id = interface_tag['tag_type_id'] @@ -46,7 +46,7 @@ class DeleteInterfaceTag(Method): interfaces = Interfaces (self.api, interface_tag['interface_id']) if not interfaces: - raise PLCInvalidArgument, "No such interface %d"%interface_tag['interface_id'] + raise PLCInvalidArgument("No such interface %d"%interface_tag['interface_id']) interface=interfaces[0] # check authorizations diff --git a/PLC/Methods/DeleteKey.py b/PLC/Methods/DeleteKey.py index 51c40d41..7653fa92 100644 --- a/PLC/Methods/DeleteKey.py +++ b/PLC/Methods/DeleteKey.py @@ -27,15 +27,15 @@ class DeleteKey(Method): # Get associated key details keys = Keys(self.api, [key_id]) if not keys: - raise PLCInvalidArgument, "No such key" + raise PLCInvalidArgument("No such key") key = keys[0] if key['peer_id'] is not None: - raise PLCInvalidArgument, "Not a local key" + raise PLCInvalidArgument("Not a local key") if 'admin' not in self.caller['roles']: if key['key_id'] not in self.caller['key_ids']: - raise PLCPermissionDenied, "Key must be associated with your account" + raise PLCPermissionDenied("Key must be associated with your account") key.delete() diff --git a/PLC/Methods/DeleteKeyType.py b/PLC/Methods/DeleteKeyType.py index 34d43394..81bbd566 100644 --- a/PLC/Methods/DeleteKeyType.py +++ b/PLC/Methods/DeleteKeyType.py @@ -26,7 +26,7 @@ class DeleteKeyType(Method): def call(self, auth, name): key_types = KeyTypes(self.api, [name]) if not key_types: - raise PLCInvalidArgument, "No such key type" + raise PLCInvalidArgument("No such key type") key_type = key_types[0] key_type.delete() diff --git a/PLC/Methods/DeleteLeases.py b/PLC/Methods/DeleteLeases.py index fef501b8..6914c989 100644 --- a/PLC/Methods/DeleteLeases.py +++ b/PLC/Methods/DeleteLeases.py @@ -30,7 +30,7 @@ class DeleteLeases(Method): # Get associated lease details leases = Leases(self.api, lease_ids) if len(leases) != len(lease_ids): - raise PLCInvalidArgument, "Could not find all leases %r"%lease_ids + raise PLCInvalidArgument("Could not find all leases %r"%lease_ids) # fetch related slices slices = Slices(self.api, [ lease['slice_id'] for lease in leases],['slice_id','person_ids']) @@ -42,13 +42,13 @@ class DeleteLeases(Method): if 'admin' not in self.caller['roles']: slice=slice_map[lease['slice_id']] # check slices only once - if not slice.has_key('verified'): + if 'verified' not in slice: if self.caller['person_id'] in slice['person_ids']: pass elif 'pi' not in self.caller['roles']: - raise PLCPermissionDenied, "Not a member of slice %r"%slice['name'] + raise PLCPermissionDenied("Not a member of slice %r"%slice['name']) elif slice['site_id'] not in self.caller['site_ids']: - raise PLCPermissionDenied, "Slice %r not associated with any of your sites"%slice['name'] + raise PLCPermissionDenied("Slice %r not associated with any of your sites"%slice['name']) slice['verified']=True lease.delete() diff --git a/PLC/Methods/DeleteMessage.py b/PLC/Methods/DeleteMessage.py index daf79635..d1cb7d4c 100644 --- a/PLC/Methods/DeleteMessage.py +++ b/PLC/Methods/DeleteMessage.py @@ -25,7 +25,7 @@ class DeleteMessage(Method): # Get message information messages = Messages(self.api, [message_id]) if not messages: - raise PLCInvalidArgument, "No such message" + raise PLCInvalidArgument("No such message") message = messages[0] message.delete() diff --git a/PLC/Methods/DeleteNetworkMethod.py b/PLC/Methods/DeleteNetworkMethod.py index b40442ce..14a4b57e 100644 --- a/PLC/Methods/DeleteNetworkMethod.py +++ b/PLC/Methods/DeleteNetworkMethod.py @@ -27,7 +27,7 @@ class DeleteNetworkMethod(Method): def call(self, auth, name): network_methods = NetworkMethods(self.api, [name]) if not network_methods: - raise PLCInvalidArgument, "No such network method" + raise PLCInvalidArgument("No such network method") network_method = network_methods[0] network_method.delete() diff --git a/PLC/Methods/DeleteNetworkType.py b/PLC/Methods/DeleteNetworkType.py index 1a0539e3..dbb6e870 100644 --- a/PLC/Methods/DeleteNetworkType.py +++ b/PLC/Methods/DeleteNetworkType.py @@ -27,7 +27,7 @@ class DeleteNetworkType(Method): def call(self, auth, name): network_types = NetworkTypes(self.api, [name]) if not network_types: - raise PLCInvalidArgument, "No such network type" + raise PLCInvalidArgument("No such network type") network_type = network_types[0] network_type.delete() diff --git a/PLC/Methods/DeleteNode.py b/PLC/Methods/DeleteNode.py index a819b248..c2b689c4 100644 --- a/PLC/Methods/DeleteNode.py +++ b/PLC/Methods/DeleteNode.py @@ -28,11 +28,11 @@ class DeleteNode(Method): # Get account information nodes = Nodes(self.api, [node_id_or_hostname]) if not nodes: - raise PLCInvalidArgument, "No such node" + raise PLCInvalidArgument("No such node") node = nodes[0] if node['peer_id'] is not None: - raise PLCInvalidArgument, "Not a local node" + raise PLCInvalidArgument("Not a local node") # If we are not an admin, make sure that the caller is a # member of the site at which the node is located. @@ -41,7 +41,7 @@ class DeleteNode(Method): assert self.caller is not None if node['site_id'] not in self.caller['site_ids']: - raise PLCPermissionDenied, "Not allowed to delete nodes from specified site" + raise PLCPermissionDenied("Not allowed to delete nodes from specified site") node_id=node['node_id'] site_id=node['site_id'] diff --git a/PLC/Methods/DeleteNodeFromPCU.py b/PLC/Methods/DeleteNodeFromPCU.py index 892d77fb..2688cd6d 100644 --- a/PLC/Methods/DeleteNodeFromPCU.py +++ b/PLC/Methods/DeleteNodeFromPCU.py @@ -30,14 +30,14 @@ class DeleteNodeFromPCU(Method): # Get node nodes = Nodes(self.api, [node_id_or_hostname]) if not nodes: - raise PLCInvalidArgument, "No such node" + raise PLCInvalidArgument("No such node") node = nodes[0] # Get PCU pcus = PCUs(self.api, [pcu_id]) if not pcus: - raise PLCInvalidArgument, "No such PCU" + raise PLCInvalidArgument("No such PCU") pcu = pcus[0] @@ -49,7 +49,7 @@ class DeleteNodeFromPCU(Method): ok = True break if not ok: - raise PLCPermissionDenied, "Not allowed to update that PCU" + raise PLCPermissionDenied("Not allowed to update that PCU") # Removed node from PCU diff --git a/PLC/Methods/DeleteNodeGroup.py b/PLC/Methods/DeleteNodeGroup.py index 812af118..ef646f90 100644 --- a/PLC/Methods/DeleteNodeGroup.py +++ b/PLC/Methods/DeleteNodeGroup.py @@ -28,7 +28,7 @@ class DeleteNodeGroup(Method): # Get account information nodegroups = NodeGroups(self.api, [node_group_id_or_name]) if not nodegroups: - raise PLCInvalidArgument, "No such node group" + raise PLCInvalidArgument("No such node group") nodegroup = nodegroups[0] diff --git a/PLC/Methods/DeleteNodeTag.py b/PLC/Methods/DeleteNodeTag.py index 2afa446f..7bc529ab 100644 --- a/PLC/Methods/DeleteNodeTag.py +++ b/PLC/Methods/DeleteNodeTag.py @@ -35,7 +35,7 @@ class DeleteNodeTag(Method): def call(self, auth, node_tag_id): node_tags = NodeTags(self.api, [node_tag_id]) if not node_tags: - raise PLCInvalidArgument, "No such node tag %r"%node_tag_id + raise PLCInvalidArgument("No such node tag %r"%node_tag_id) node_tag = node_tags[0] tag_type_id = node_tag['tag_type_id'] @@ -43,7 +43,7 @@ class DeleteNodeTag(Method): nodes = Nodes (self.api, node_tag['node_id']) if not nodes: - raise PLCInvalidArgument, "No such node %d"%node_tag['node_id'] + raise PLCInvalidArgument("No such node %d"%node_tag['node_id']) node=nodes[0] # check authorizations diff --git a/PLC/Methods/DeleteNodeType.py b/PLC/Methods/DeleteNodeType.py index e6e9579d..679fdb90 100644 --- a/PLC/Methods/DeleteNodeType.py +++ b/PLC/Methods/DeleteNodeType.py @@ -27,7 +27,7 @@ class DeleteNodeType(Method): def call(self, auth, name): node_types = NodeTypes(self.api, [name]) if not node_types: - raise PLCInvalidArgument, "No such node type" + raise PLCInvalidArgument("No such node type") node_type = node_types[0] node_type.delete() diff --git a/PLC/Methods/DeletePCU.py b/PLC/Methods/DeletePCU.py index fe59abc9..a420403b 100644 --- a/PLC/Methods/DeletePCU.py +++ b/PLC/Methods/DeletePCU.py @@ -27,12 +27,12 @@ class DeletePCU(Method): # Get associated PCU details pcus = PCUs(self.api, [pcu_id]) if not pcus: - raise PLCInvalidArgument, "No such PCU" + raise PLCInvalidArgument("No such PCU") pcu = pcus[0] if 'admin' not in self.caller['roles']: if pcu['site_id'] not in self.caller['site_ids']: - raise PLCPermissionDenied, "Not allowed to update that PCU" + raise PLCPermissionDenied("Not allowed to update that PCU") pcu.delete() diff --git a/PLC/Methods/DeletePCUProtocolType.py b/PLC/Methods/DeletePCUProtocolType.py index 1ff162be..d05daa00 100644 --- a/PLC/Methods/DeletePCUProtocolType.py +++ b/PLC/Methods/DeletePCUProtocolType.py @@ -24,7 +24,7 @@ class DeletePCUProtocolType(Method): def call(self, auth, protocol_type_id): protocol_types = PCUProtocolTypes(self.api, [protocol_type_id]) if not protocol_types: - raise PLCInvalidArgument, "No such pcu protocol type" + raise PLCInvalidArgument("No such pcu protocol type") protocol_type = protocol_types[0] protocol_type.delete() diff --git a/PLC/Methods/DeletePCUType.py b/PLC/Methods/DeletePCUType.py index 6d545cb8..752ea32e 100644 --- a/PLC/Methods/DeletePCUType.py +++ b/PLC/Methods/DeletePCUType.py @@ -24,7 +24,7 @@ class DeletePCUType(Method): def call(self, auth, pcu_type_id): pcu_types = PCUTypes(self.api, [pcu_type_id]) if not pcu_types: - raise PLCInvalidArgument, "No such pcu type" + raise PLCInvalidArgument("No such pcu type") pcu_type = pcu_types[0] pcu_type.delete() diff --git a/PLC/Methods/DeletePeer.py b/PLC/Methods/DeletePeer.py index ed0cd795..0de6bec9 100644 --- a/PLC/Methods/DeletePeer.py +++ b/PLC/Methods/DeletePeer.py @@ -27,7 +27,7 @@ class DeletePeer(Method): # Get account information peers = Peers(self.api, [peer_id_or_name]) if not peers: - raise PLCInvalidArgument, "No such peer" + raise PLCInvalidArgument("No such peer") peer = peers[0] peer.delete() diff --git a/PLC/Methods/DeletePerson.py b/PLC/Methods/DeletePerson.py index e85d2e91..c214270f 100644 --- a/PLC/Methods/DeletePerson.py +++ b/PLC/Methods/DeletePerson.py @@ -29,18 +29,18 @@ class DeletePerson(Method): # Get account information persons = Persons(self.api, [person_id_or_email]) if not persons: - raise PLCInvalidArgument, "No such account" + raise PLCInvalidArgument("No such account") person = persons[0] if person['peer_id'] is not None: - raise PLCInvalidArgument, "Not a local account" + raise PLCInvalidArgument("Not a local account") # Authenticated function assert self.caller is not None # Check if we can update this account if not self.caller.can_update(person): - raise PLCPermissionDenied, "Not allowed to delete specified account" + raise PLCPermissionDenied("Not allowed to delete specified account") person.delete() diff --git a/PLC/Methods/DeletePersonFromSite.py b/PLC/Methods/DeletePersonFromSite.py index cf4379d1..11df6a75 100644 --- a/PLC/Methods/DeletePersonFromSite.py +++ b/PLC/Methods/DeletePersonFromSite.py @@ -30,20 +30,20 @@ class DeletePersonFromSite(Method): # Get account information persons = Persons(self.api, [person_id_or_email]) if not persons: - raise PLCInvalidArgument, "No such account" + raise PLCInvalidArgument("No such account") person = persons[0] if person['peer_id'] is not None: - raise PLCInvalidArgument, "Not a local account" + raise PLCInvalidArgument("Not a local account") # Get site information sites = Sites(self.api, [site_id_or_login_base]) if not sites: - raise PLCInvalidArgument, "No such site" + raise PLCInvalidArgument("No such site") site = sites[0] if site['peer_id'] is not None: - raise PLCInvalidArgument, "Not a local site" + raise PLCInvalidArgument("Not a local site") if site['site_id'] in person['site_ids']: site.remove_person(person) diff --git a/PLC/Methods/DeletePersonFromSlice.py b/PLC/Methods/DeletePersonFromSlice.py index dbec6843..e47ebbea 100644 --- a/PLC/Methods/DeletePersonFromSlice.py +++ b/PLC/Methods/DeletePersonFromSlice.py @@ -29,26 +29,26 @@ class DeletePersonFromSlice(Method): # Get account information persons = Persons(self.api, [person_id_or_email]) if not persons: - raise PLCInvalidArgument, "No such account %s"%person_id_or_email + raise PLCInvalidArgument("No such account %s"%person_id_or_email) person = persons[0] # Get slice information slices = Slices(self.api, [slice_id_or_name]) if not slices: - raise PLCInvalidArgument, "No such slice %s"%slice_id_or_name + raise PLCInvalidArgument("No such slice %s"%slice_id_or_name) slice = slices[0] # N.B. Allow foreign users to be added to local slices and # local users to be added to foreign slices (and, of course, # local users to be added to local slices). if person['peer_id'] is not None and slice['peer_id'] is not None: - raise PLCInvalidArgument, "Cannot delete foreign users from foreign slices" + raise PLCInvalidArgument("Cannot delete foreign users from foreign slices") # If we are not admin, make sure the caller is a pi # of the site associated with the slice if 'admin' not in self.caller['roles']: if slice['site_id'] not in self.caller['site_ids']: - raise PLCPermissionDenied, "Not allowed to delete users from slice %s"%slice_id_or_name + raise PLCPermissionDenied("Not allowed to delete users from slice %s"%slice_id_or_name) if slice['slice_id'] in person['slice_ids']: slice.remove_person(person) diff --git a/PLC/Methods/DeletePersonTag.py b/PLC/Methods/DeletePersonTag.py index 6b748d3f..09865b4d 100644 --- a/PLC/Methods/DeletePersonTag.py +++ b/PLC/Methods/DeletePersonTag.py @@ -34,7 +34,7 @@ class DeletePersonTag(Method): def call(self, auth, person_tag_id): person_tags = PersonTags(self.api, [person_tag_id]) if not person_tags: - raise PLCInvalidArgument, "No such person tag %r"%person_tag_id + raise PLCInvalidArgument("No such person tag %r"%person_tag_id) person_tag = person_tags[0] tag_type_id = person_tag['tag_type_id'] @@ -42,7 +42,7 @@ class DeletePersonTag(Method): persons = Persons (self.api, person_tag['person_id']) if not persons: - raise PLCInvalidArgument, "No such person %d"%person_tag['person_id'] + raise PLCInvalidArgument("No such person %d"%person_tag['person_id']) person=persons[0] # check authorizations diff --git a/PLC/Methods/DeleteRole.py b/PLC/Methods/DeleteRole.py index aac09137..680fc6d7 100644 --- a/PLC/Methods/DeleteRole.py +++ b/PLC/Methods/DeleteRole.py @@ -29,7 +29,7 @@ class DeleteRole(Method): def call(self, auth, role_id_or_name): roles = Roles(self.api, [role_id_or_name]) if not roles: - raise PLCInvalidArgument, "No such role" + raise PLCInvalidArgument("No such role") role = roles[0] role.delete() diff --git a/PLC/Methods/DeleteRoleFromPerson.py b/PLC/Methods/DeleteRoleFromPerson.py index 4deacf60..3a9b2958 100644 --- a/PLC/Methods/DeleteRoleFromPerson.py +++ b/PLC/Methods/DeleteRoleFromPerson.py @@ -31,29 +31,29 @@ class DeleteRoleFromPerson(Method): # Get role roles = Roles(self.api, [role_id_or_name]) if not roles: - raise PLCInvalidArgument, "Invalid role '%s'" % unicode(role_id_or_name) + raise PLCInvalidArgument("Invalid role '%s'" % str(role_id_or_name)) role = roles[0] # Get account information persons = Persons(self.api, [person_id_or_email]) if not persons: - raise PLCInvalidArgument, "No such account" + raise PLCInvalidArgument("No such account") person = persons[0] if person['peer_id'] is not None: - raise PLCInvalidArgument, "Not a local account" + raise PLCInvalidArgument("Not a local account") # Authenticated function assert self.caller is not None # Check if we can update this account if not self.caller.can_update(person): - raise PLCPermissionDenied, "Not allowed to update specified account" + raise PLCPermissionDenied("Not allowed to update specified account") # Can only revoke lesser (higher) roles from others if 'admin' not in self.caller['roles'] and \ role['role_id'] <= min(self.caller['role_ids']): - raise PLCPermissionDenied, "Not allowed to revoke that role" + raise PLCPermissionDenied("Not allowed to revoke that role") if role['role_id'] in person['role_ids']: person.remove_role(role) diff --git a/PLC/Methods/DeleteRoleFromTagType.py b/PLC/Methods/DeleteRoleFromTagType.py index cdce6fa6..91bd27b2 100644 --- a/PLC/Methods/DeleteRoleFromTagType.py +++ b/PLC/Methods/DeleteRoleFromTagType.py @@ -31,13 +31,13 @@ class DeleteRoleFromTagType(Method): # Get role roles = Roles(self.api, [role_id_or_name]) if not roles: - raise PLCInvalidArgument, "Invalid role '%s'" % unicode(role_id_or_name) + raise PLCInvalidArgument("Invalid role '%s'" % str(role_id_or_name)) role = roles[0] # Get subject tag type tag_types = TagTypes(self.api, [tag_type_id_or_tagname]) if not tag_types: - raise PLCInvalidArgument, "No such tag type" + raise PLCInvalidArgument("No such tag type") tag_type = tag_types[0] # Authenticated function @@ -45,7 +45,7 @@ class DeleteRoleFromTagType(Method): # Only admins if 'admin' not in self.caller['roles']: - raise PLCInvalidArgument, "Not allowed to revoke that role" + raise PLCInvalidArgument("Not allowed to revoke that role") if role['role_id'] in tag_type['role_ids']: tag_type.remove_role(role) diff --git a/PLC/Methods/DeleteSession.py b/PLC/Methods/DeleteSession.py index 3898f515..9ad5bd6d 100644 --- a/PLC/Methods/DeleteSession.py +++ b/PLC/Methods/DeleteSession.py @@ -18,11 +18,11 @@ class DeleteSession(Method): def call(self, auth): - assert auth.has_key('session') + assert 'session' in auth sessions = Sessions(self.api, [auth['session']]) if not sessions: - raise PLCAPIError, "No such session" + raise PLCAPIError("No such session") session = sessions[0] session.delete() diff --git a/PLC/Methods/DeleteSite.py b/PLC/Methods/DeleteSite.py index db2b294b..2e68d6aa 100644 --- a/PLC/Methods/DeleteSite.py +++ b/PLC/Methods/DeleteSite.py @@ -31,11 +31,11 @@ class DeleteSite(Method): # Get account information sites = Sites(self.api, [site_id_or_login_base]) if not sites: - raise PLCInvalidArgument, "No such site" + raise PLCInvalidArgument("No such site") site = sites[0] if site['peer_id'] is not None: - raise PLCInvalidArgument, "Not a local site" + raise PLCInvalidArgument("Not a local site") site.delete() diff --git a/PLC/Methods/DeleteSiteTag.py b/PLC/Methods/DeleteSiteTag.py index 036ffda7..726420aa 100644 --- a/PLC/Methods/DeleteSiteTag.py +++ b/PLC/Methods/DeleteSiteTag.py @@ -36,7 +36,7 @@ class DeleteSiteTag(Method): def call(self, auth, site_tag_id): site_tags = SiteTags(self.api, [site_tag_id]) if not site_tags: - raise PLCInvalidArgument, "No such site tag %r"%site_tag_id + raise PLCInvalidArgument("No such site tag %r"%site_tag_id) site_tag = site_tags[0] tag_type_id = site_tag['tag_type_id'] @@ -44,7 +44,7 @@ class DeleteSiteTag(Method): sites = Sites (self.api, site_tag['site_id']) if not sites: - raise PLCInvalidArgument, "No such site %d"%site_tag['site_id'] + raise PLCInvalidArgument("No such site %d"%site_tag['site_id']) site=sites[0] # check authorizations diff --git a/PLC/Methods/DeleteSlice.py b/PLC/Methods/DeleteSlice.py index 297f8a94..49df6ea0 100644 --- a/PLC/Methods/DeleteSlice.py +++ b/PLC/Methods/DeleteSlice.py @@ -28,19 +28,19 @@ class DeleteSlice(Method): def call(self, auth, slice_id_or_name): slices = Slices(self.api, [slice_id_or_name]) if not slices: - raise PLCInvalidArgument, "No such slice" + raise PLCInvalidArgument("No such slice") slice = slices[0] if slice['peer_id'] is not None: - raise PLCInvalidArgument, "Not a local slice" + raise PLCInvalidArgument("Not a local slice") if 'admin' not in self.caller['roles']: if self.caller['person_id'] in slice['person_ids']: pass elif 'pi' not in self.caller['roles']: - raise PLCPermissionDenied, "Not a member of the specified slice" + raise PLCPermissionDenied("Not a member of the specified slice") elif slice['site_id'] not in self.caller['site_ids']: - raise PLCPermissionDenied, "Specified slice not associated with any of your sites" + raise PLCPermissionDenied("Specified slice not associated with any of your sites") slice.delete() self.event_objects = {'Slice': [slice['slice_id']]} diff --git a/PLC/Methods/DeleteSliceFromNodes.py b/PLC/Methods/DeleteSliceFromNodes.py index 1a82ad11..f896fe92 100644 --- a/PLC/Methods/DeleteSliceFromNodes.py +++ b/PLC/Methods/DeleteSliceFromNodes.py @@ -29,19 +29,19 @@ class DeleteSliceFromNodes(Method): # Get slice information slices = Slices(self.api, [slice_id_or_name]) if not slices: - raise PLCInvalidArgument, "No such slice" + raise PLCInvalidArgument("No such slice") slice = slices[0] if slice['peer_id'] is not None: - raise PLCInvalidArgument, "Not a local slice" + raise PLCInvalidArgument("Not a local slice") if 'admin' not in self.caller['roles']: if self.caller['person_id'] in slice['person_ids']: pass elif 'pi' not in self.caller['roles']: - raise PLCPermissionDenied, "Not a member of the specified slice" + raise PLCPermissionDenied("Not a member of the specified slice") elif slice['site_id'] not in self.caller['site_ids']: - raise PLCPermissionDenied, "Specified slice not associated with any of your sites" + raise PLCPermissionDenied("Specified slice not associated with any of your sites") # Remove slice from all nodes found @@ -49,7 +49,7 @@ class DeleteSliceFromNodes(Method): nodes = Nodes(self.api, node_id_or_hostname_list) for node in nodes: if slice['peer_id'] is not None and node['peer_id'] is not None: - raise PLCPermissionDenied, "Not allowed to remove peer slice from peer node" + raise PLCPermissionDenied("Not allowed to remove peer slice from peer node") if slice['slice_id'] in node['slice_ids']: slice.remove_node(node, commit = False) diff --git a/PLC/Methods/DeleteSliceFromNodesWhitelist.py b/PLC/Methods/DeleteSliceFromNodesWhitelist.py index c369966f..0e2b67a7 100644 --- a/PLC/Methods/DeleteSliceFromNodesWhitelist.py +++ b/PLC/Methods/DeleteSliceFromNodesWhitelist.py @@ -32,17 +32,17 @@ class DeleteSliceFromNodesWhitelist(Method): # Get slice information slices = Slices(self.api, [slice_id_or_name]) if not slices: - raise PLCInvalidArgument, "No such slice" + raise PLCInvalidArgument("No such slice") slice = slices[0] if slice['peer_id'] is not None: - raise PLCInvalidArgument, "Not a local slice" + raise PLCInvalidArgument("Not a local slice") # Get specified nodes, add them to the slice nodes = Nodes(self.api, node_id_or_hostname_list) for node in nodes: if node['peer_id'] is not None: - raise PLCInvalidArgument, "%s not a local node" % node['hostname'] + raise PLCInvalidArgument("%s not a local node" % node['hostname']) if slice['slice_id'] in node['slice_ids_whitelist']: slice.delete_from_node_whitelist(node, commit = False) diff --git a/PLC/Methods/DeleteSliceInstantiation.py b/PLC/Methods/DeleteSliceInstantiation.py index 5098a9de..b5d8e510 100644 --- a/PLC/Methods/DeleteSliceInstantiation.py +++ b/PLC/Methods/DeleteSliceInstantiation.py @@ -26,7 +26,7 @@ class DeleteSliceInstantiation(Method): def call(self, auth, instantiation): slice_instantiations = SliceInstantiations(self.api, [instantiation]) if not slice_instantiations: - raise PLCInvalidArgument, "No such slice instantiation state" + raise PLCInvalidArgument("No such slice instantiation state") slice_instantiation = slice_instantiations[0] slice_instantiation.delete() diff --git a/PLC/Methods/DeleteSliceTag.py b/PLC/Methods/DeleteSliceTag.py index ec11b41f..2e133a83 100644 --- a/PLC/Methods/DeleteSliceTag.py +++ b/PLC/Methods/DeleteSliceTag.py @@ -39,7 +39,7 @@ class DeleteSliceTag(Method): def call(self, auth, slice_tag_id): slice_tags = SliceTags(self.api, [slice_tag_id]) if not slice_tags: - raise PLCInvalidArgument, "No such slice attribute" + raise PLCInvalidArgument("No such slice attribute") slice_tag = slice_tags[0] tag_type_id = slice_tag['tag_type_id'] @@ -47,7 +47,7 @@ class DeleteSliceTag(Method): slices = Slices(self.api, [slice_tag['slice_id']]) if not slices: - raise PLCInvalidArgument, "No such slice %d"%slice_tag['slice_id'] + raise PLCInvalidArgument("No such slice %d"%slice_tag['slice_id']) slice = slices[0] assert slice_tag['slice_tag_id'] in slice['slice_tag_ids'] diff --git a/PLC/Methods/DeleteTagType.py b/PLC/Methods/DeleteTagType.py index d5d57c90..db18b93a 100644 --- a/PLC/Methods/DeleteTagType.py +++ b/PLC/Methods/DeleteTagType.py @@ -28,7 +28,7 @@ class DeleteTagType(Method): def call(self, auth, tag_type_id_or_name): tag_types = TagTypes(self.api, [tag_type_id_or_name]) if not tag_types: - raise PLCInvalidArgument, "No such node tag type" + raise PLCInvalidArgument("No such node tag type") tag_type = tag_types[0] tag_type.delete() diff --git a/PLC/Methods/GenerateNodeConfFile.py b/PLC/Methods/GenerateNodeConfFile.py index 68876d27..f2af06c8 100644 --- a/PLC/Methods/GenerateNodeConfFile.py +++ b/PLC/Methods/GenerateNodeConfFile.py @@ -35,17 +35,17 @@ class GenerateNodeConfFile(Method): # Get node information nodes = Nodes(self.api, [node_id_or_hostname]) if not nodes: - raise PLCInvalidArgument, "No such node" + raise PLCInvalidArgument("No such node") node = nodes[0] if node['peer_id'] is not None: - raise PLCInvalidArgument, "Not a local node" + raise PLCInvalidArgument("Not a local node") # If we are not an admin, make sure that the caller is a # member of the site at which the node is located. if 'admin' not in self.caller['roles']: if node['site_id'] not in self.caller['site_ids']: - raise PLCPermissionDenied, "Not allowed to generate a configuration file for that node" + raise PLCPermissionDenied("Not allowed to generate a configuration file for that node") # Get interfaces for this node primary = None @@ -55,18 +55,18 @@ class GenerateNodeConfFile(Method): primary = interface break if primary is None: - raise PLCInvalidArgument, "No primary network configured" + raise PLCInvalidArgument("No primary network configured") # Split hostname into host and domain parts parts = node['hostname'].split(".", 1) if len(parts) < 2: - raise PLCInvalidArgument, "Node hostname is invalid" + raise PLCInvalidArgument("Node hostname is invalid") host = parts[0] domain = parts[1] if regenerate_node_key: # Generate 32 random bytes - bytes = random.sample(xrange(0, 256), 32) + bytes = random.sample(range(0, 256), 32) # Base64 encode their string representation node['key'] = base64.b64encode("".join(map(chr, bytes))) # XXX Boot Manager cannot handle = in the key diff --git a/PLC/Methods/GetBootMedium.py b/PLC/Methods/GetBootMedium.py index 26b83727..289fdf4e 100644 --- a/PLC/Methods/GetBootMedium.py +++ b/PLC/Methods/GetBootMedium.py @@ -40,7 +40,7 @@ allowed_actions = { # compute a new key def compute_key(): # Generate 32 random bytes - bytes = random.sample(xrange(0, 256), 32) + bytes = random.sample(range(0, 256), 32) # Base64 encode their string representation key = base64.b64encode("".join(map(chr, bytes))) # Boot Manager cannot handle = in the key @@ -344,7 +344,7 @@ class GetBootMedium(Method): if filedir: if not os.path.exists(filedir): try: - os.makedirs (filedir,0777) + os.makedirs (filedir,0o777) except: raise PLCPermissionDenied("Could not create dir {}".format(filedir)) @@ -481,7 +481,7 @@ class GetBootMedium(Method): else: node = None # compute a 8 bytes random number - tempbytes = random.sample (xrange(0,256), 8); + tempbytes = random.sample (range(0,256), 8); def hexa2 (c): return chr((c>>4)+65) + chr ((c&16)+65) nodename = "".join(map(hexa2,tempbytes)) @@ -553,8 +553,8 @@ class GetBootMedium(Method): # create the workdir if needed if not os.path.isdir(self.WORKDIR): try: - os.makedirs(self.WORKDIR,0777) - os.chmod(self.WORKDIR,0777) + os.makedirs(self.WORKDIR,0o777) + os.chmod(self.WORKDIR,0o777) except: raise PLCPermissionDenied("Could not create dir {}".format(self.WORKDIR)) diff --git a/PLC/Methods/GetKeys.py b/PLC/Methods/GetKeys.py index 70b3a4db..434859f2 100644 --- a/PLC/Methods/GetKeys.py +++ b/PLC/Methods/GetKeys.py @@ -36,6 +36,6 @@ class GetKeys(Method): # If we are not admin, make sure to only return our own keys if isinstance(self.caller, Person) and \ 'admin' not in self.caller['roles']: - keys = filter(lambda key: key['key_id'] in self.caller['key_ids'], keys) + keys = [key for key in keys if key['key_id'] in self.caller['key_ids']] return keys diff --git a/PLC/Methods/GetNodeFlavour.py b/PLC/Methods/GetNodeFlavour.py index f357b2f3..96485c50 100644 --- a/PLC/Methods/GetNodeFlavour.py +++ b/PLC/Methods/GetNodeFlavour.py @@ -87,7 +87,7 @@ class GetNodeFlavour(Method): # Get node information nodes = Nodes(self.api, [node_id_or_name]) if not nodes: - raise PLCInvalidArgument, "No such node %r"%node_id_or_name + raise PLCInvalidArgument("No such node %r"%node_id_or_name) node = nodes[0] node_id = node['node_id'] diff --git a/PLC/Methods/GetPCUs.py b/PLC/Methods/GetPCUs.py index 8b3b91fb..c59fa40f 100644 --- a/PLC/Methods/GetPCUs.py +++ b/PLC/Methods/GetPCUs.py @@ -62,7 +62,7 @@ class GetPCUs(Method): # Filter out PCUs that are not viewable if not (isinstance(self.caller, Person) and 'admin' in self.caller['roles']): - pcus = filter(lambda pcu: pcu['pcu_id'] in valid_pcu_ids, pcus) + pcus = [pcu for pcu in pcus if pcu['pcu_id'] in valid_pcu_ids] # Remove pcu_id if not specified if added_fields: diff --git a/PLC/Methods/GetPeerData.py b/PLC/Methods/GetPeerData.py index 86193d0f..0cd4f80f 100644 --- a/PLC/Methods/GetPeerData.py +++ b/PLC/Methods/GetPeerData.py @@ -76,7 +76,7 @@ class GetPeerData(Method): # filter out system slices system_slice_ids = SliceTags(self.api, {'name': 'system', 'value': '1'}).dict('slice_id') - slices = Slices(self.api, {'peer_id': None,'~slice_id':system_slice_ids.keys()}, slice_fields) + slices = Slices(self.api, {'peer_id': None,'~slice_id':list(system_slice_ids.keys())}, slice_fields) sites = Sites(self.api, {'peer_id': None}, site_fields) @@ -98,7 +98,7 @@ class GetPeerData(Method): # filter out system slices system_slice_ids = SliceTags(self.api, {'name': 'system', 'value': '1'}).dict('slice_id') filtered_slices = Slices(self.api, {'peer_id': None, - '~slice_id':system_slice_ids.keys()}, slice_fields) + '~slice_id':list(system_slice_ids.keys())}, slice_fields) filtered_sites = Sites(self.api, {'peer_id': None}, site_fields) diff --git a/PLC/Methods/GetPersons.py b/PLC/Methods/GetPersons.py index 263c6635..e9ffcb8a 100644 --- a/PLC/Methods/GetPersons.py +++ b/PLC/Methods/GetPersons.py @@ -35,8 +35,7 @@ class GetPersons(Method): ] # Filter out password field - return_fields = dict(filter(lambda (field, value): field not in hidden_fields, - Person.fields.items())) + return_fields = dict([field_value for field_value in list(Person.fields.items()) if field_value[0] not in hidden_fields]) returns = [return_fields] def call(self, auth, person_filter = None, return_fields = None): @@ -67,10 +66,9 @@ class GetPersons(Method): # Filter out password field if return_fields: - return_fields = filter(lambda field: field not in hidden_fields, - return_fields) + return_fields = [field for field in return_fields if field not in hidden_fields] else: - return_fields = self.return_fields.keys() + return_fields = list(self.return_fields.keys()) # Must query at least person_id, site_ids, and role_ids (see # Person.can_view() and below). @@ -85,7 +83,7 @@ class GetPersons(Method): # Filter out accounts that are not viewable if isinstance(self.caller, Person) and \ 'admin' not in self.caller['roles']: - persons = filter(self.caller.can_view, persons) + persons = list(filter(self.caller.can_view, persons)) # Remove added fields if not specified if added_fields: diff --git a/PLC/Methods/GetPlcRelease.py b/PLC/Methods/GetPlcRelease.py index 796ae7ea..07b16f8e 100644 --- a/PLC/Methods/GetPlcRelease.py +++ b/PLC/Methods/GetPlcRelease.py @@ -34,7 +34,7 @@ class GetPlcRelease(Method): matchers = {} result = {} - for field in regexps.keys(): + for field in list(regexps.keys()): matchers[field] = re.compile(regexps[field]) result[field]={} @@ -44,16 +44,16 @@ class GetPlcRelease(Method): line=line.strip() if comment_matcher.match(line): continue - for field in regexps.keys(): + for field in list(regexps.keys()): m=matchers[field].match(line) if m: (key,value)=m.groups(['key','value']) result[field][key]=value break else: - if not result.has_key('unexpected'): + if 'unexpected' not in result: result['unexpected']="" result['unexpected'] += (line+"\n") except: - raise PLCNotImplemented, 'Cannot open /etc/myplc-release' + raise PLCNotImplemented('Cannot open /etc/myplc-release') return result diff --git a/PLC/Methods/GetSession.py b/PLC/Methods/GetSession.py index 82dccbfd..1e05765c 100644 --- a/PLC/Methods/GetSession.py +++ b/PLC/Methods/GetSession.py @@ -24,7 +24,7 @@ class GetSession(Method): def call(self, auth, expires=None): # Authenticated with a session key, just return it - if auth.has_key('session'): + if 'session' in auth: return auth['session'] session = Session(self.api) diff --git a/PLC/Methods/GetSliceFamily.py b/PLC/Methods/GetSliceFamily.py index 910fe2fd..236045ac 100644 --- a/PLC/Methods/GetSliceFamily.py +++ b/PLC/Methods/GetSliceFamily.py @@ -33,7 +33,7 @@ class GetSliceFamily(Method): # Get slice information slices = Slices(self.api, [slice_id_or_name]) if not slices: - raise PLCInvalidArgument, "No such slice %r"%slice_id_or_name + raise PLCInvalidArgument("No such slice %r"%slice_id_or_name) slice = slices[0] slice_id = slice['slice_id'] diff --git a/PLC/Methods/GetSliceKeys.py b/PLC/Methods/GetSliceKeys.py index 2e4e758e..fba76e94 100644 --- a/PLC/Methods/GetSliceKeys.py +++ b/PLC/Methods/GetSliceKeys.py @@ -64,9 +64,9 @@ class GetSliceKeys(Method): slice_filter = valid_slice_ids if return_fields: - slice_return_fields = filter(lambda field: field in slice_fields, return_fields) - person_return_fields = filter(lambda field: field in person_fields, return_fields) - key_return_fields = filter(lambda field: field in key_fields, return_fields) + slice_return_fields = [field for field in return_fields if field in slice_fields] + person_return_fields = [field for field in return_fields if field in person_fields] + key_return_fields = [field for field in return_fields if field in key_fields] else: slice_return_fields = slice_fields person_return_fields = person_fields @@ -83,13 +83,13 @@ class GetSliceKeys(Method): # Get the slices all_slices = Slices(self.api, slice_filter, slice_return_fields).dict('slice_id') - slice_ids = all_slices.keys() - slices = all_slices.values() + slice_ids = list(all_slices.keys()) + slices = list(all_slices.values()) # Filter out slices that are not viewable if isinstance(self.caller, Person) and \ 'admin' not in self.caller['roles']: - slices = filter(lambda slice: slice['slice_id'] in valid_slice_ids, slices) + slices = [slice for slice in slices if slice['slice_id'] in valid_slice_ids] # Get the persons person_ids = set() @@ -97,8 +97,8 @@ class GetSliceKeys(Method): person_ids.update(slice['person_ids']) all_persons = Persons(self.api, list(person_ids), person_return_fields).dict('person_id') - person_ids = all_persons.keys() - persons = all_persons.values() + person_ids = list(all_persons.keys()) + persons = list(all_persons.values()) # Get the keys key_ids = set() @@ -106,8 +106,8 @@ class GetSliceKeys(Method): key_ids.update(person['key_ids']) all_keys = Keys(self.api, list(key_ids), key_return_fields).dict('key_id') - key_ids = all_keys.keys() - keys = all_keys.values() + key_ids = list(all_keys.keys()) + keys = list(all_keys.values()) # Create slice_keys list slice_keys = [] @@ -125,9 +125,9 @@ class GetSliceKeys(Method): continue for key_id in person['key_ids']: key = all_keys[key_id] - slice_key.update(dict(filter(lambda (k, v): k in slice_fields, slice.items()))) - slice_key.update(dict(filter(lambda (k, v): k in person_fields, person.items()))) - slice_key.update(dict(filter(lambda (k, v): k in key_fields, key.items()))) + slice_key.update(dict([k_v for k_v in list(slice.items()) if k_v[0] in slice_fields])) + slice_key.update(dict([k_v1 for k_v1 in list(person.items()) if k_v1[0] in person_fields])) + slice_key.update(dict([k_v2 for k_v2 in list(key.items()) if k_v2[0] in key_fields])) slice_keys.append(slice_key.copy()) return slice_keys diff --git a/PLC/Methods/GetSliceTags.py b/PLC/Methods/GetSliceTags.py index c6db287c..91035fc1 100644 --- a/PLC/Methods/GetSliceTags.py +++ b/PLC/Methods/GetSliceTags.py @@ -81,9 +81,7 @@ class GetSliceTags(Method): # Filter out slice attributes that are not viewable if isinstance(self.caller, Person) and \ 'admin' not in self.caller['roles']: - slice_tags = filter(lambda slice_tag: \ - slice_tag['slice_tag_id'] in valid_slice_tag_ids, - slice_tags) + slice_tags = [slice_tag for slice_tag in slice_tags if slice_tag['slice_tag_id'] in valid_slice_tag_ids] # Remove slice_tag_id if not specified if added_fields: diff --git a/PLC/Methods/GetSliceTicket.py b/PLC/Methods/GetSliceTicket.py index 13c78400..5a34c47c 100644 --- a/PLC/Methods/GetSliceTicket.py +++ b/PLC/Methods/GetSliceTicket.py @@ -42,15 +42,15 @@ class GetSliceTicket(Method): def call(self, auth, slice_id_or_name): slices = Slices(self.api, [slice_id_or_name]) if not slices: - raise PLCInvalidArgument, "No such slice" + raise PLCInvalidArgument("No such slice") slice = slices[0] # Allow peers to obtain tickets for their own slices if slice['peer_id'] is not None: if not isinstance(self.caller, Peer): - raise PLCInvalidArgument, "Not a local slice" + raise PLCInvalidArgument("Not a local slice") elif slice['peer_id'] != self.caller['peer_id']: - raise PLCInvalidArgument, "Only the authoritative peer may obtain tickets for that slice" + raise PLCInvalidArgument("Only the authoritative peer may obtain tickets for that slice") # Tickets are the canonicalized XML-RPC methodResponse # representation of a partial GetSlivers() response, i.e., diff --git a/PLC/Methods/GetSlices.py b/PLC/Methods/GetSlices.py index c06fbe29..fff2c393 100644 --- a/PLC/Methods/GetSlices.py +++ b/PLC/Methods/GetSlices.py @@ -71,7 +71,7 @@ class GetSlices(Method): # Filter out slices that are not viewable if isinstance(self.caller, Person) and \ 'admin' not in self.caller['roles']: - slices = filter(lambda slice: slice['slice_id'] in valid_slice_ids, slices) + slices = [slice for slice in slices if slice['slice_id'] in valid_slice_ids] # Remove slice_id if not specified if added_fields: diff --git a/PLC/Methods/GetSlivers.py b/PLC/Methods/GetSlivers.py index 9e3b73d2..1a0349f5 100644 --- a/PLC/Methods/GetSlivers.py +++ b/PLC/Methods/GetSlivers.py @@ -22,9 +22,10 @@ from PLC.Methods.GetSliceFamily import GetSliceFamily from PLC.PersonTags import PersonTag,PersonTags from PLC.Accessors.Accessors_standard import * +from functools import reduce # XXX used to check if slice expiration time is sane -MAXINT = 2L**31-1 +MAXINT = 2**31-1 # slice_filter essentially contains the slice_ids for the relevant slices (on the node + system & delegated slices) def get_slivers(api, caller, auth, slice_filter, node = None): @@ -43,7 +44,7 @@ def get_slivers(api, caller, auth, slice_filter, node = None): # 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']) # Get user account keys @@ -132,11 +133,11 @@ def get_slivers(api, caller, auth, slice_filter, node = None): def sanitize_for_pickle (obj): if (isinstance(obj, dict)): parent = dict(obj) - for k in parent.keys(): parent[k] = sanitize_for_pickle (parent[k]) + for k in list(parent.keys()): parent[k] = sanitize_for_pickle (parent[k]) return parent elif (isinstance(obj, list)): parent = list(obj) - parent = map(sanitize_for_pickle, parent) + parent = list(map(sanitize_for_pickle, parent)) return parent else: return obj @@ -218,22 +219,22 @@ class GetSlivers(Method): if isinstance(self.caller, Node): node = self.caller else: - raise PLCInvalidArgument, "'node_id_or_hostname' not specified" + raise PLCInvalidArgument("'node_id_or_hostname' not specified") else: nodes = Nodes(self.api, [node_id_or_hostname]) if not nodes: - raise PLCInvalidArgument, "No such node" + raise PLCInvalidArgument("No such node") node = nodes[0] if node['peer_id'] is not None: - raise PLCInvalidArgument, "Not a local node" + raise PLCInvalidArgument("Not a local node") # Get interface information interfaces = Interfaces(self.api, node['interface_ids']) # Get node group information nodegroups = NodeGroups(self.api, node['nodegroup_ids']).dict('groupname') - groups = nodegroups.keys() + groups = list(nodegroups.keys()) # Get all (enabled) configuration files all_conf_files = ConfFiles(self.api, {'enabled': True}).dict() @@ -242,7 +243,7 @@ class GetSlivers(Method): # Global configuration files are the default. If multiple # entries for the same global configuration file exist, it is # undefined which one takes precedence. - for conf_file in all_conf_files.values(): + for conf_file in list(all_conf_files.values()): if not conf_file['node_ids'] and not conf_file['nodegroup_ids']: conf_files[conf_file['dest']] = conf_file @@ -250,7 +251,7 @@ class GetSlivers(Method): # ones. If a node belongs to multiple node groups for which # the same configuration file is defined, it is undefined # which one takes precedence. - for nodegroup in nodegroups.values(): + for nodegroup in list(nodegroups.values()): for conf_file_id in nodegroup['conf_file_ids']: if conf_file_id in all_conf_files: conf_file = all_conf_files[conf_file_id] @@ -268,12 +269,12 @@ class GetSlivers(Method): # Get system slices system_slice_tags = SliceTags(self.api, {'tagname': 'system', 'value': '1'}).dict('slice_id') - system_slice_ids = system_slice_tags.keys() + system_slice_ids = list(system_slice_tags.keys()) # Get nm-controller slices # xxx Thierry: should these really be exposed regardless of their mapping to nodes ? controller_and_delegated_slices = Slices(self.api, {'instantiation': ['nm-controller', 'delegated']}, ['slice_id']).dict('slice_id') - controller_and_delegated_slice_ids = controller_and_delegated_slices.keys() + controller_and_delegated_slice_ids = list(controller_and_delegated_slices.keys()) slice_ids = system_slice_ids + controller_and_delegated_slice_ids + node['slice_ids'] slivers = get_slivers(self.api, self.caller, auth, slice_ids, node) @@ -295,8 +296,8 @@ class GetSlivers(Method): site = Sites (api,site_id_or_name,['person_ids'])[0] all_site_persons = site['person_ids'] all_site_person_tags = PersonTags(self.api,{'person_id':all_site_persons,'tagname':'isrootonsite'},['value','person_id']) - site_root_person_tags = filter(lambda r:r['value']=='true',all_site_person_tags) - site_root_person_ids = map(lambda r:r['person_id'],site_root_person_tags) + site_root_person_tags = [r for r in all_site_person_tags if r['value']=='true'] + site_root_person_ids = [r['person_id'] for r in site_root_person_tags] key_ids = reduce (reduce_flatten_list, [ p['key_ids'] for p in \ Persons(api,{ 'person_id':site_root_person_ids, @@ -341,7 +342,7 @@ class GetSlivers(Method): # XMPP config for omf federation try: if not self.api.config.PLC_OMF_ENABLED: - raise Exception,"OMF not enabled" + raise Exception("OMF not enabled") xmpp={'server':self.api.config.PLC_OMF_XMPP_SERVER} except: xmpp={'server':None} @@ -370,7 +371,7 @@ class GetSlivers(Method): 'hostname': node['hostname'], 'interfaces': interfaces, 'groups': groups, - 'conf_files': conf_files.values(), + 'conf_files': list(conf_files.values()), 'initscripts': initscripts, 'slivers': slivers, 'accounts': accounts, diff --git a/PLC/Methods/NotifyPersons.py b/PLC/Methods/NotifyPersons.py index 70c273d6..9704f45d 100644 --- a/PLC/Methods/NotifyPersons.py +++ b/PLC/Methods/NotifyPersons.py @@ -32,7 +32,7 @@ class NotifyPersons(Method): persons = Persons(self.api, person_filter, ['person_id', 'first_name', 'last_name', 'email']) if not persons: - raise PLCInvalidArgument, "No such user(s)" + raise PLCInvalidArgument("No such user(s)") # Send email sendmail(self.api, diff --git a/PLC/Methods/RebootNode.py b/PLC/Methods/RebootNode.py index ed15ce39..a6e0439d 100644 --- a/PLC/Methods/RebootNode.py +++ b/PLC/Methods/RebootNode.py @@ -34,7 +34,7 @@ class RebootNode(Method): # Get account information nodes = Nodes(self.api, [node_id_or_hostname]) if not nodes: - raise PLCInvalidArgument, "No such node" + raise PLCInvalidArgument("No such node") node = nodes[0] @@ -45,11 +45,11 @@ class RebootNode(Method): # member of the site at which the node is located. if 'admin' not in self.caller['roles']: if node['site_id'] not in self.caller['site_ids']: - raise PLCPermissionDenied, "Not allowed to delete nodes from specified site" + raise PLCPermissionDenied("Not allowed to delete nodes from specified site") session = node['session'] if not session: - raise PLCInvalidArgument, "No session key on record for that node (i.e., has never successfully booted)" + raise PLCInvalidArgument("No session key on record for that node (i.e., has never successfully booted)") session = session.strip() # Only use the hostname as a backup, try to use the primary ID @@ -63,7 +63,7 @@ class RebootNode(Method): try: udp_pod(host, session) - except socket.error, e: + except socket.error as e: # Ignore socket errors pass diff --git a/PLC/Methods/RebootNodeWithPCU.py b/PLC/Methods/RebootNodeWithPCU.py index 2126a2ef..ba9f3080 100644 --- a/PLC/Methods/RebootNodeWithPCU.py +++ b/PLC/Methods/RebootNodeWithPCU.py @@ -42,7 +42,7 @@ class RebootNodeWithPCU(Method): # Get account information nodes = Nodes(self.api, [node_id_or_hostname]) if not nodes: - raise PLCInvalidArgument, "No such node" + raise PLCInvalidArgument("No such node") if testrun is None: testrun = False @@ -56,17 +56,17 @@ class RebootNodeWithPCU(Method): # member of the site at which the node is located. if 'admin' not in self.caller['roles']: if node['site_id'] not in self.caller['site_ids']: - raise PLCPermissionDenied, "Not allowed to reboot nodes from specified site" + raise PLCPermissionDenied("Not allowed to reboot nodes from specified site") # Verify that the node has pcus associated with it. pcus = PCUs(self.api, {'pcu_id' : node['pcu_ids']} ) if not pcus: - raise PLCInvalidArgument, "No PCUs associated with Node" + raise PLCInvalidArgument("No PCUs associated with Node") pcu = pcus[0] if not external_dependency: - raise PLCNotImplemented, "Could not load external module to attempt reboot" + raise PLCNotImplemented("Could not load external module to attempt reboot") # model, hostname, port, # i = pcu['node_ids'].index(node['node_id']) diff --git a/PLC/Methods/RefreshPeer.py b/PLC/Methods/RefreshPeer.py index 7af8569f..d5ad9299 100644 --- a/PLC/Methods/RefreshPeer.py +++ b/PLC/Methods/RefreshPeer.py @@ -83,13 +83,13 @@ class FileLock: if (time.time() - os.stat(self.fpath).st_ctime) > self.expire: try: os.unlink(self.fpath) - except Exception, e: + except Exception as e: message('FileLock.lock({}) : {}'.format(self.fpath, e)) return False try: self.fd = open(self.fpath, 'w') fcntl.flock(self.fd, fcntl.LOCK_EX | fcntl.LOCK_NB) - except IOError, e: + except IOError as e: message('FileLock.lock({}) : {}'.format(self.fpath, e)) return False return True @@ -98,7 +98,7 @@ class FileLock: try: fcntl.flock(self.fd, fcntl.LOCK_UN | fcntl.LOCK_NB) self.fd.close() - except IOError, e: + except IOError as e: message('FileLock.unlock({}) : {}'.format(self.fpath, e)) @@ -163,14 +163,14 @@ class RefreshPeer(Method): file_lock = FileLock("/tmp/refresh-peer-{peername}.lock" .format(peername=peername)) if not file_lock.lock(): - raise Exception, "Another instance of RefreshPeer is running." + raise Exception("Another instance of RefreshPeer is running.") try: ret_val = self.real_call(auth, peer_id_or_peername) - except Exception, e: + except Exception as e: file_lock.unlock() logger.exception("RefreshPeer caught exception - BEG") message("RefreshPeer caught exception - END") - raise Exception, e + raise Exception(e) file_lock.unlock() return ret_val @@ -178,7 +178,7 @@ class RefreshPeer(Method): # Get peer peers = Peers(self.api, [peer_id_or_peername]) if not peers: - raise PLCInvalidArgument, "No such peer '{}'".format(unicode(peer_id_or_peername)) + raise PLCInvalidArgument("No such peer '{}'".format(str(peer_id_or_peername))) peer = peers[0] peer_id = peer['peer_id'] peername = peer['peername'] @@ -281,7 +281,7 @@ class RefreshPeer(Method): synced = {} # Delete stale objects - for peer_object_id, object in objects.iteritems(): + for peer_object_id, object in objects.items(): if peer_object_id not in peer_objects: object.delete(commit=commit_mode) message("{} {} {} deleted" @@ -330,7 +330,7 @@ class RefreshPeer(Method): return True # Add/update new/existing objects - for peer_object_id, peer_object in peer_objects.iteritems(): + for peer_object_id, peer_object in peer_objects.items(): peer_object_name = "" if secondary_key: peer_object_name = "({})".format(peer_object[secondary_key]) @@ -381,7 +381,7 @@ class RefreshPeer(Method): id=peer_object_id, mode=commit_mode)) try: object.sync(commit=commit_mode) - except PLCInvalidArgument, err: + except PLCInvalidArgument as err: # XXX Log an event instead of printing to logfile # skip if validation fails message("Warning: {peername} Skipping invalid {classname} ({err})\n{object}" @@ -426,7 +426,7 @@ class RefreshPeer(Method): # Compare only the columns returned by the GetPeerData() call if peer_tables['Sites']: - columns = peer_tables['Sites'][0].keys() + columns = list(peer_tables['Sites'][0].keys()) columns = intersect(columns, Site.fields) else: columns = None @@ -441,7 +441,7 @@ class RefreshPeer(Method): peer_sites = sync(old_peer_sites, sites_at_peer, Site, ignore(columns, RefreshPeer.ignore_site_fields)) - for peer_site_id, site in peer_sites.iteritems(): + for peer_site_id, site in peer_sites.items(): # Bind any newly cached sites to peer if peer_site_id not in old_peer_sites: peer.add_site(site, peer_site_id, commit=commit_mode) @@ -466,7 +466,7 @@ class RefreshPeer(Method): # Compare only the columns returned by the GetPeerData() call if peer_tables['Keys']: - columns = peer_tables['Keys'][0].keys() + columns = list(peer_tables['Keys'][0].keys()) columns = intersect(columns, Key.fields) else: columns = None @@ -478,7 +478,7 @@ class RefreshPeer(Method): for key in peer_tables['Keys']]) # Fix up key_type references - for peer_key_id, key in keys_at_peer.items(): + for peer_key_id, key in list(keys_at_peer.items()): if key['key_type'] not in key_types: # XXX Log an event instead of printing to logfile message("Warning: Skipping invalid {peername} key {key}" @@ -489,7 +489,7 @@ class RefreshPeer(Method): # Synchronize new set (still keyed on foreign key_id) peer_keys = sync(old_peer_keys, keys_at_peer, Key, ignore(columns, RefreshPeer.ignore_key_fields)) - for peer_key_id, key in peer_keys.iteritems(): + for peer_key_id, key in peer_keys.items(): # Bind any newly cached keys to peer if peer_key_id not in old_peer_keys: peer.add_key(key, peer_key_id, commit=commit_mode) @@ -508,7 +508,7 @@ class RefreshPeer(Method): # Compare only the columns returned by the GetPeerData() call if peer_tables['Persons']: - columns = peer_tables['Persons'][0].keys() + columns = list(peer_tables['Persons'][0].keys()) columns = intersect(columns, Person.fields) else: columns = None @@ -533,9 +533,9 @@ class RefreshPeer(Method): # transcoder : retrieve a local key_id from a peer_key_id key_transcoder = dict([(key['key_id'], peer_key_id) - for peer_key_id, key in peer_keys.iteritems()]) + for peer_key_id, key in peer_keys.items()]) - for peer_person_id, person in peer_persons.iteritems(): + for peer_person_id, person in peer_persons.items(): # Bind any newly cached users to peer if peer_person_id not in old_peer_persons: peer.add_person(person, peer_person_id, commit=commit_mode) @@ -590,7 +590,7 @@ class RefreshPeer(Method): # Compare only the columns returned by the GetPeerData() call if peer_tables['Nodes']: - columns = peer_tables['Nodes'][0].keys() + columns = list(peer_tables['Nodes'][0].keys()) columns = intersect(columns, Node.fields) else: columns = Node.fields @@ -602,7 +602,7 @@ class RefreshPeer(Method): for node in peer_tables['Nodes']]) # Fix up site_id and boot_states references - for peer_node_id, node in nodes_at_peer.items(): + for peer_node_id, node in list(nodes_at_peer.items()): errors = [] if node['site_id'] not in peer_sites: errors.append("invalid (or disabled) site {}".format(node['site_id'])) @@ -622,7 +622,7 @@ class RefreshPeer(Method): peer_nodes = sync(old_peer_nodes, nodes_at_peer, Node, ignore(columns, RefreshPeer.ignore_node_fields)) - for peer_node_id, node in peer_nodes.iteritems(): + for peer_node_id, node in peer_nodes.items(): # Bind any newly cached foreign nodes to peer if peer_node_id not in old_peer_nodes: peer.add_node(node, peer_node_id, commit=commit_mode) @@ -669,7 +669,7 @@ class RefreshPeer(Method): # Compare only the columns returned by the GetPeerData() call if peer_tables['Slices']: - columns = peer_tables['Slices'][0].keys() + columns = list(peer_tables['Slices'][0].keys()) columns = intersect(columns, Slice.fields) else: columns = None @@ -681,7 +681,7 @@ class RefreshPeer(Method): for slice in peer_tables['Slices']]) # Fix up site_id, instantiation, and creator_person_id references - for peer_slice_id, slice in slices_at_peer.items(): + for peer_slice_id, slice in list(slices_at_peer.items()): errors = [] if slice['site_id'] not in peer_sites: errors.append("invalid site {}".format(slice['site_id'])) @@ -710,11 +710,11 @@ class RefreshPeer(Method): message('(7) Dealing with Nodes in Slices') # transcoder : retrieve a local node_id from a peer_node_id node_transcoder = dict([(node['node_id'], peer_node_id) - for peer_node_id, node in peer_nodes.iteritems()]) + for peer_node_id, node in peer_nodes.items()]) person_transcoder = dict([(person['person_id'], peer_person_id) - for peer_person_id, person in peer_persons.iteritems()]) + for peer_person_id, person in peer_persons.items()]) - for peer_slice_id, slice in peer_slices.iteritems(): + for peer_slice_id, slice in peer_slices.items(): # Bind any newly cached foreign slices to peer if peer_slice_id not in old_peer_slices: peer.add_slice(slice, peer_slice_id, commit=commit_mode) @@ -764,7 +764,7 @@ class RefreshPeer(Method): # The one-line map/filter style is nicer but ineffective here old_slice_person_ids = [] for person_id in slice['person_ids']: - if not person_transcoder.has_key(person_id): + if person_id not in person_transcoder: message('WARNING : person_id {person_id} in {slicename} not transcodable (1) - skipped' .format(person_id=person_id, slicename=slice['name'])) elif person_transcoder[person_id] not in peer_persons: @@ -806,7 +806,7 @@ class RefreshPeer(Method): message('(8) Dealing with Persons in Sites') - for peer_site_id, site in peer_sites.iteritems(): + for peer_site_id, site in peer_sites.items(): # Site as viewed by peer peer_site = sites_at_peer[peer_site_id] @@ -845,7 +845,7 @@ class RefreshPeer(Method): roles = Roles(self.api) roles_dict = dict([(role['role_id'], role) for role in roles]) - for peer_person_id, person in peer_persons.iteritems(): + for peer_person_id, person in peer_persons.items(): # Person as viewed by peer peer_person = persons_at_peer[peer_person_id] diff --git a/PLC/Methods/ReportRunlevel.py b/PLC/Methods/ReportRunlevel.py index c2fb9ce1..deddd66d 100644 --- a/PLC/Methods/ReportRunlevel.py +++ b/PLC/Methods/ReportRunlevel.py @@ -27,11 +27,11 @@ class ReportRunlevel(Method): if not isinstance(self.caller, Node): # check admin if 'admin' not in self.caller['roles']: - raise PLCPermissionDenied, "Not allowed to update node run_level" + raise PLCPermissionDenied("Not allowed to update node run_level") nodes = Nodes(self.api, [node_id_or_hostname]) if not nodes: - raise PLCInvalidArgument, "No such node" + raise PLCInvalidArgument("No such node") else: nodes = [self.caller] @@ -56,6 +56,6 @@ class ReportRunlevel(Method): message="run level " + node['hostname'] + ":" if 'run_level' in report_fields: message += str(former_level) + "->" + report_fields['run_level'] - message += ", ".join( [ k + "->" + v for (k,v) in report_fields.items() if k not in ['run_level'] ] ) + message += ", ".join( [ k + "->" + v for (k,v) in list(report_fields.items()) if k not in ['run_level'] ] ) return 1 diff --git a/PLC/Methods/ResetPassword.py b/PLC/Methods/ResetPassword.py index 8e9da53a..ca488a34 100644 --- a/PLC/Methods/ResetPassword.py +++ b/PLC/Methods/ResetPassword.py @@ -1,7 +1,7 @@ import random import base64 import time -import urllib +import urllib.request, urllib.parse, urllib.error from types import StringTypes @@ -51,21 +51,21 @@ class ResetPassword(Method): filter['peer_id']=None persons = Persons(self.api, filter) if not persons: - raise PLCInvalidArgument, "No such account" + raise PLCInvalidArgument("No such account") person = persons[0] if person['peer_id'] is not None: - raise PLCInvalidArgument, "Not a local account" + raise PLCInvalidArgument("Not a local account") if not person['enabled']: - raise PLCInvalidArgument, "Account must be enabled" + raise PLCInvalidArgument("Account must be enabled") # Be paranoid and deny password resets for admins if 'admin' in person['roles']: - raise PLCInvalidArgument, "Cannot reset admin passwords" + raise PLCInvalidArgument("Cannot reset admin passwords") # Generate 32 random bytes - bytes = random.sample(xrange(0, 256), 32) + bytes = random.sample(range(0, 256), 32) # Base64 encode their string representation random_key = base64.b64encode("".join(map(chr, bytes))) @@ -73,9 +73,9 @@ class ResetPassword(Method): if person['verification_key'] is None or \ person['verification_expires'] is None or \ person['verification_expires'] < time.time(): - raise PLCPermissionDenied, "Verification key has expired" + raise PLCPermissionDenied("Verification key has expired") elif person['verification_key'] != verification_key: - raise PLCPermissionDenied, "Verification key incorrect" + raise PLCPermissionDenied("Verification key incorrect") else: # Reset password to random string person['password'] = random_key @@ -88,7 +88,7 @@ class ResetPassword(Method): # Only allow one reset at a time if person['verification_expires'] is not None and \ person['verification_expires'] > time.time(): - raise PLCPermissionDenied, "Password reset request already pending" + raise PLCPermissionDenied("Password reset request already pending") if verification_expires is None: verification_expires = int(time.time() + (24 * 60 * 60)) @@ -110,7 +110,7 @@ class ResetPassword(Method): 'PLC_WWW_SSL_PORT': self.api.config.PLC_WWW_SSL_PORT, 'person_id': person['person_id'], # Will be used in a URL, so must quote appropriately - 'verification_key': urllib.quote_plus(random_key), + 'verification_key': urllib.parse.quote_plus(random_key), 'password': random_key, 'email': person['email']} diff --git a/PLC/Methods/ResolveSlices.py b/PLC/Methods/ResolveSlices.py index 6eec238c..6e58b1ef 100644 --- a/PLC/Methods/ResolveSlices.py +++ b/PLC/Methods/ResolveSlices.py @@ -36,7 +36,7 @@ class ResolveSlices(Method): def call(self, auth, slice_filter = None): # Must query at least slice_id (see below) - return_fields = self.applicable_fields.keys() + return_fields = list(self.applicable_fields.keys()) # pass expires=0 slices = Slices(self.api, slice_filter, return_fields, 0) return slices diff --git a/PLC/Methods/RetrieveSlicePersonKeys.py b/PLC/Methods/RetrieveSlicePersonKeys.py index 86a927d7..e851fe2b 100644 --- a/PLC/Methods/RetrieveSlicePersonKeys.py +++ b/PLC/Methods/RetrieveSlicePersonKeys.py @@ -7,6 +7,7 @@ from PLC.Auth import Auth from PLC.Slices import Slice, Slices from PLC.Persons import Person, Persons from PLC.Keys import Key, Keys +from functools import reduce class RetrieveSlicePersonKeys(Method): """ diff --git a/PLC/Methods/SetPersonPrimarySite.py b/PLC/Methods/SetPersonPrimarySite.py index 644826b6..9fcb2ec7 100644 --- a/PLC/Methods/SetPersonPrimarySite.py +++ b/PLC/Methods/SetPersonPrimarySite.py @@ -31,11 +31,11 @@ class SetPersonPrimarySite(Method): # Get account information persons = Persons(self.api, [person_id_or_email]) if not persons: - raise PLCInvalidArgument, "No such account" + raise PLCInvalidArgument("No such account") person = persons[0] if person['peer_id'] is not None: - raise PLCInvalidArgument, "Not a local account" + raise PLCInvalidArgument("Not a local account") # Authenticated function assert self.caller is not None @@ -43,19 +43,19 @@ class SetPersonPrimarySite(Method): # Non-admins can only update their own primary site if 'admin' not in self.caller['roles'] and \ self.caller['person_id'] != person['person_id']: - raise PLCPermissionDenied, "Not allowed to update specified account" + raise PLCPermissionDenied("Not allowed to update specified account") # Get site information sites = Sites(self.api, [site_id_or_login_base]) if not sites: - raise PLCInvalidArgument, "No such site" + raise PLCInvalidArgument("No such site") site = sites[0] if site['peer_id'] is not None: - raise PLCInvalidArgument, "Not a local site" + raise PLCInvalidArgument("Not a local site") if site['site_id'] not in person['site_ids']: - raise PLCInvalidArgument, "Not a member of the specified site" + raise PLCInvalidArgument("Not a member of the specified site") person.set_primary_site(site) diff --git a/PLC/Methods/SliceExtendedInfo.py b/PLC/Methods/SliceExtendedInfo.py index 26fbd9a9..331493c1 100644 --- a/PLC/Methods/SliceExtendedInfo.py +++ b/PLC/Methods/SliceExtendedInfo.py @@ -42,7 +42,7 @@ class SliceExtendedInfo(Method): slice_filter = slice_name_list slices = Slices(self.api, slice_filter) if not slices: - raise PLCInvalidArgument, "No such slice" + raise PLCInvalidArgument("No such slice") if 'admin' not in self.caller['roles']: # Get slices that we are able to view @@ -55,7 +55,7 @@ class SliceExtendedInfo(Method): if not valid_slice_ids: return [] - slices = filter(lambda slice: slice['slice_id'] in valid_slice_ids, slices) + slices = [slice for slice in slices if slice['slice_id'] in valid_slice_ids] for slice in slices: index = slices.index(slice) diff --git a/PLC/Methods/SliceGetTicket.py b/PLC/Methods/SliceGetTicket.py index 27c08323..045fdfc2 100644 --- a/PLC/Methods/SliceGetTicket.py +++ b/PLC/Methods/SliceGetTicket.py @@ -62,7 +62,7 @@ class PrettyXMLGenerator(XMLGenerator): self.ignorableWhitespace("".join(self.indents)) self.write('<' + name) - for (name, value) in attrs.items(): + for (name, value) in list(attrs.items()): self.write(' %s=%s' % (name, quoteattr(value))) self.write('/>') @@ -84,15 +84,15 @@ class SliceGetTicket(GetSliceTicket): def call(self, auth, slice_id_or_name): slices = Slices(self.api, [slice_id_or_name]) if not slices: - raise PLCInvalidArgument, "No such slice" + raise PLCInvalidArgument("No such slice") slice = slices[0] # Allow peers to obtain tickets for their own slices if slice['peer_id'] is not None: - raise PLCInvalidArgument, "Not a local slice" + raise PLCInvalidArgument("Not a local slice") if slice['instantiation'] != 'delegated': - raise PLCInvalidArgument, "Not in delegated state" + raise PLCInvalidArgument("Not in delegated state") nodes = Nodes(self.api, slice['node_ids']).dict() persons = Persons(self.api, slice['person_ids']).dict() @@ -109,39 +109,39 @@ class SliceGetTicket(GetSliceTicket): # xml.startElement('slice', {'id': str(slice['slice_id']), - 'name': unicode(slice['name']), - 'expiry': unicode(int(slice['expires']))}) + 'name': str(slice['name']), + 'expiry': str(int(slice['expires']))}) # xml.startElement('nodes', {}) for node_id in slice['node_ids']: - if not nodes.has_key(node_id): + if node_id not in nodes: continue node = nodes[node_id] # xml.simpleElement('node', {'id': str(node['node_id']), - 'hostname': unicode(node['hostname'])}) + 'hostname': str(node['hostname'])}) # xml.endElement('nodes') # xml.startElement('users', {}) for person_id in slice['person_ids']: - if not persons.has_key(person_id): + if person_id not in persons: continue user = persons[person_id] # xml.simpleElement('user', - {'person_id': unicode(user['person_id']), - 'email': unicode(user['email'])}) + {'person_id': str(user['person_id']), + 'email': str(user['email'])}) # xml.endElement('users') # xml.startElement('rspec', {}) for slice_tag_id in slice['slice_tag_ids']: - if not slice_tags.has_key(slice_tag_id): + if slice_tag_id not in slice_tags: continue slice_tag = slice_tags[slice_tag_id] @@ -187,15 +187,15 @@ class SliceGetTicket(GetSliceTicket): type = "string" # - xml.startElement('resource', {'name': unicode(attribute_name)}) + xml.startElement('resource', {'name': str(attribute_name)}) # xml.startElement('value', - {'name': unicode(value_name), + {'name': str(value_name), 'type': type}, newl = False) # element value - xml.characters(unicode(value)) + xml.characters(str(value)) # xml.endElement('value', indent = False) @@ -228,7 +228,7 @@ class SliceGetTicket(GetSliceTicket): if not hasattr(self.api.config, 'PLC_API_TICKET_KEY') or \ not os.path.exists(self.api.config.PLC_API_TICKET_KEY): - raise PLCAPIError, "Slice ticket signing key not found" + raise PLCAPIError("Slice ticket signing key not found") ticket.flush() @@ -244,6 +244,6 @@ class SliceGetTicket(GetSliceTicket): ticket.close() if rc: - raise PLCAPIError, err + raise PLCAPIError(err) return signed_ticket diff --git a/PLC/Methods/SliceInfo.py b/PLC/Methods/SliceInfo.py index 2182c6ee..f7a35beb 100644 --- a/PLC/Methods/SliceInfo.py +++ b/PLC/Methods/SliceInfo.py @@ -42,7 +42,7 @@ class SliceInfo(Method): slice_filter = slice_name_list slices = Slices(self.api, slice_filter) if not slices: - raise PLCInvalidArgument, "No such slice" + raise PLCInvalidArgument("No such slice") if 'admin' not in self.caller['roles']: # Get slices that we are able to view @@ -55,7 +55,7 @@ class SliceInfo(Method): if not valid_slice_ids: return [] - slices = filter(lambda slice: slice['slice_id'] in valid_slice_ids, slices) + slices = [slice for slice in slices if slice['slice_id'] in valid_slice_ids] for slice in slices: diff --git a/PLC/Methods/SliceListNames.py b/PLC/Methods/SliceListNames.py index 01f6257a..9dfeb0bd 100644 --- a/PLC/Methods/SliceListNames.py +++ b/PLC/Methods/SliceListNames.py @@ -38,7 +38,7 @@ class SliceListNames(GetSlices): slices = GetSlices.call(self, auth, slice_filter) if not slices: - raise PLCInvalidArgument, "No such slice" + raise PLCInvalidArgument("No such slice") slice_names = [slice['name'] for slice in slices] diff --git a/PLC/Methods/UnBindObjectFromPeer.py b/PLC/Methods/UnBindObjectFromPeer.py index 156f9765..b90475b3 100644 --- a/PLC/Methods/UnBindObjectFromPeer.py +++ b/PLC/Methods/UnBindObjectFromPeer.py @@ -43,8 +43,8 @@ class UnBindObjectFromPeer(Method): # invoke e.g. Nodes ({'node_id':node_id}) objs=class_obj(self.api,{id_name:object_id}) if len(objs) != 1: - raise PLCInvalidArgument,"Cannot locate object, type=%s id=%d"%\ - (type,object_id) + raise PLCInvalidArgument("Cannot locate object, type=%s id=%d"%\ + (type,object_id)) return objs[0] @@ -52,11 +52,11 @@ class UnBindObjectFromPeer(Method): object_type = object_type.lower() if object_type not in self.known_types: - raise PLCInvalidArgument, 'Unrecognized object type %s'%object_type + raise PLCInvalidArgument('Unrecognized object type %s'%object_type) peers=Peers(self.api,{'shortname':shortname.upper()}) if len(peers) !=1: - raise PLCInvalidArgument, 'No such peer with shortname %s'%shortname + raise PLCInvalidArgument('No such peer with shortname %s'%shortname) peer=peers[0] object = self.locate_object (object_type, object_id) diff --git a/PLC/Methods/UpdateAddress.py b/PLC/Methods/UpdateAddress.py index 03acb37c..9ef7a24b 100644 --- a/PLC/Methods/UpdateAddress.py +++ b/PLC/Methods/UpdateAddress.py @@ -4,7 +4,7 @@ from PLC.Parameter import Parameter, Mixed from PLC.Addresses import Address, Addresses from PLC.Auth import Auth -can_update = lambda (field, value): field in \ +can_update = lambda field_value: field_value[0] in \ ['line1', 'line2', 'line3', 'city', 'state', 'postalcode', 'country'] @@ -20,7 +20,7 @@ class UpdateAddress(Method): roles = ['admin', 'pi'] - address_fields = dict(filter(can_update, Address.fields.items())) + address_fields = dict(list(filter(can_update, list(Address.fields.items())))) accepts = [ Auth(), @@ -31,17 +31,17 @@ class UpdateAddress(Method): returns = Parameter(int, '1 if successful') def call(self, auth, address_id, address_fields): - address_fields = dict(filter(can_update, address_fields.items())) + address_fields = dict(list(filter(can_update, list(address_fields.items())))) # Get associated address details addresses = Addresses(self.api, [address_id]) if not addresses: - raise PLCInvalidArgument, "No such address" + raise PLCInvalidArgument("No such address") address = addresses[0] if 'admin' not in self.caller['roles']: if address['site_id'] not in self.caller['site_ids']: - raise PLCPermissionDenied, "Address must be associated with one of your sites" + raise PLCPermissionDenied("Address must be associated with one of your sites") address.update(address_fields) address.sync() @@ -49,6 +49,6 @@ class UpdateAddress(Method): # Logging variables self.event_objects = {'Address': [address['address_id']]} self.message = 'Address %d updated: %s' % \ - (address['address_id'], ", ".join(address_fields.keys())) + (address['address_id'], ", ".join(list(address_fields.keys()))) return 1 diff --git a/PLC/Methods/UpdateAddressType.py b/PLC/Methods/UpdateAddressType.py index 2b42ade6..800d9ee8 100644 --- a/PLC/Methods/UpdateAddressType.py +++ b/PLC/Methods/UpdateAddressType.py @@ -4,7 +4,7 @@ from PLC.Parameter import Parameter, Mixed from PLC.AddressTypes import AddressType, AddressTypes from PLC.Auth import Auth -can_update = lambda (field, value): field in ['name', 'description'] +can_update = lambda field_value: field_value[0] in ['name', 'description'] class UpdateAddressType(Method): """ @@ -16,7 +16,7 @@ class UpdateAddressType(Method): roles = ['admin'] - address_type_fields = dict(filter(can_update, AddressType.fields.items())) + address_type_fields = dict(list(filter(can_update, list(AddressType.fields.items())))) accepts = [ Auth(), @@ -28,11 +28,11 @@ class UpdateAddressType(Method): returns = Parameter(int, '1 if successful') def call(self, auth, address_type_id_or_name, address_type_fields): - address_type_fields = dict(filter(can_update, address_type_fields.items())) + address_type_fields = dict(list(filter(can_update, list(address_type_fields.items())))) address_types = AddressTypes(self.api, [address_type_id_or_name]) if not address_types: - raise PLCInvalidArgument, "No such address type" + raise PLCInvalidArgument("No such address type") address_type = address_types[0] address_type.update(address_type_fields) diff --git a/PLC/Methods/UpdateConfFile.py b/PLC/Methods/UpdateConfFile.py index 5ae37fbd..9e4b95db 100644 --- a/PLC/Methods/UpdateConfFile.py +++ b/PLC/Methods/UpdateConfFile.py @@ -4,7 +4,7 @@ from PLC.Parameter import Parameter, Mixed from PLC.ConfFiles import ConfFile, ConfFiles from PLC.Auth import Auth -can_update = lambda (field, value): field not in \ +can_update = lambda field_value: field_value[0] not in \ ['conf_file_id', 'node_ids', 'nodegroup_ids'] class UpdateConfFile(Method): @@ -17,7 +17,7 @@ class UpdateConfFile(Method): roles = ['admin'] - conf_file_fields = dict(filter(can_update, ConfFile.fields.items())) + conf_file_fields = dict(list(filter(can_update, list(ConfFile.fields.items())))) accepts = [ Auth(), @@ -28,11 +28,11 @@ class UpdateConfFile(Method): returns = Parameter(int, '1 if successful') def call(self, auth, conf_file_id, conf_file_fields): - conf_file_fields = dict(filter(can_update, conf_file_fields.items())) + conf_file_fields = dict(list(filter(can_update, list(conf_file_fields.items())))) conf_files = ConfFiles(self.api, [conf_file_id]) if not conf_files: - raise PLCInvalidArgument, "No such configuration file" + raise PLCInvalidArgument("No such configuration file") conf_file = conf_files[0] conf_file.update(conf_file_fields) diff --git a/PLC/Methods/UpdateIlink.py b/PLC/Methods/UpdateIlink.py index 97b14b6f..9d0d5ea7 100644 --- a/PLC/Methods/UpdateIlink.py +++ b/PLC/Methods/UpdateIlink.py @@ -38,7 +38,7 @@ class UpdateIlink(Method): def call(self, auth, ilink_id, value): ilinks = Ilinks(self.api, [ilink_id]) if not ilinks: - raise PLCInvalidArgument, "No such ilink %r"%ilink_id + raise PLCInvalidArgument("No such ilink %r"%ilink_id) ilink = ilinks[0] src_if=Interfaces(self.api,ilink['src_interface_id'])[0] @@ -50,13 +50,13 @@ class UpdateIlink(Method): if 'admin' in self.caller['roles']: pass elif not AuthorizeHelpers.caller_may_access_tag_type (self.api, self.caller, tag_type): - raise PLCPermissionDenied, "%s, forbidden tag %s"%(self.name,tag_type['tagname']) + raise PLCPermissionDenied("%s, forbidden tag %s"%(self.name,tag_type['tagname'])) elif AuthorizeHelpers.interface_belongs_to_person (self.api, src_if, self.caller): pass elif src_if_id != dst_if_id and AuthorizeHelpers.interface_belongs_to_person (self.api, dst_if, self.caller): pass else: - raise PLCPermissionDenied, "%s: you must own either the src or dst interface"%self.name + raise PLCPermissionDenied("%s: you must own either the src or dst interface"%self.name) ilink['value'] = value ilink.sync() diff --git a/PLC/Methods/UpdateInitScript.py b/PLC/Methods/UpdateInitScript.py index f8c4eba1..d301c97d 100644 --- a/PLC/Methods/UpdateInitScript.py +++ b/PLC/Methods/UpdateInitScript.py @@ -4,7 +4,7 @@ from PLC.Parameter import Parameter, Mixed from PLC.InitScripts import InitScript, InitScripts from PLC.Auth import Auth -can_update = lambda (field, value): field not in \ +can_update = lambda field_value: field_value[0] not in \ ['initscript_id'] class UpdateInitScript(Method): @@ -17,7 +17,7 @@ class UpdateInitScript(Method): roles = ['admin'] - initscript_fields = dict(filter(can_update, InitScript.fields.items())) + initscript_fields = dict(list(filter(can_update, list(InitScript.fields.items())))) accepts = [ Auth(), @@ -28,11 +28,11 @@ class UpdateInitScript(Method): returns = Parameter(int, '1 if successful') def call(self, auth, initscript_id, initscript_fields): - initscript_fields = dict(filter(can_update, initscript_fields.items())) + initscript_fields = dict(list(filter(can_update, list(initscript_fields.items())))) initscripts = InitScripts(self.api, [initscript_id]) if not initscripts: - raise PLCInvalidArgument, "No such initscript" + raise PLCInvalidArgument("No such initscript") initscript = initscripts[0] initscript.update(initscript_fields) diff --git a/PLC/Methods/UpdateInterface.py b/PLC/Methods/UpdateInterface.py index 034780ec..5d79c0d9 100644 --- a/PLC/Methods/UpdateInterface.py +++ b/PLC/Methods/UpdateInterface.py @@ -48,12 +48,12 @@ class UpdateInterface(Method): # type checking native= Row.check_fields (native, self.accepted_fields) if rejected: - raise PLCInvalidArgument, "Cannot update Interface column(s) %r"%rejected + raise PLCInvalidArgument("Cannot update Interface column(s) %r"%rejected) # Get interface information interfaces = Interfaces(self.api, [interface_id]) if not interfaces: - raise PLCInvalidArgument, "No such interface" + raise PLCInvalidArgument("No such interface") interface = interfaces[0] @@ -65,19 +65,19 @@ class UpdateInterface(Method): if 'admin' not in self.caller['roles']: nodes = Nodes(self.api, [interface['node_id']]) if not nodes: - raise PLCPermissionDenied, "Interface is not associated with a node" + raise PLCPermissionDenied("Interface is not associated with a node") node = nodes[0] if node['site_id'] not in self.caller['site_ids']: - raise PLCPermissionDenied, "Not allowed to update interface" + raise PLCPermissionDenied("Not allowed to update interface") interface.update(native) interface.update_last_updated(commit=False) interface.sync() - for (tagname,value) in tags.iteritems(): + for (tagname,value) in tags.items(): # the tagtype instance is assumed to exist, just check that if not TagTypes(self.api,{'tagname':tagname}): - raise PLCInvalidArgument,"No such TagType %s"%tagname + raise PLCInvalidArgument("No such TagType %s"%tagname) interface_tags=InterfaceTags(self.api,{'tagname':tagname,'interface_id':interface['interface_id']}) if not interface_tags: AddInterfaceTag(self.api).__call__(auth,interface['interface_id'],tagname,value) @@ -89,6 +89,6 @@ class UpdateInterface(Method): self.message = "Interface %s updated"%interface['ip'] else: self.message = "Interface %d updated"%interface['interface_id'] - self.message += "[%s]." % ", ".join(interface_fields.keys()) + self.message += "[%s]." % ", ".join(list(interface_fields.keys())) return 1 diff --git a/PLC/Methods/UpdateInterfaceTag.py b/PLC/Methods/UpdateInterfaceTag.py index bcd6fc01..7a43720c 100644 --- a/PLC/Methods/UpdateInterfaceTag.py +++ b/PLC/Methods/UpdateInterfaceTag.py @@ -39,7 +39,7 @@ class UpdateInterfaceTag(Method): def call(self, auth, interface_tag_id, value): interface_tags = InterfaceTags(self.api, [interface_tag_id]) if not interface_tags: - raise PLCInvalidArgument, "No such interface setting %r"%interface_tag_id + raise PLCInvalidArgument("No such interface setting %r"%interface_tag_id) interface_tag = interface_tags[0] tag_type_id = interface_tag['tag_type_id'] @@ -47,7 +47,7 @@ class UpdateInterfaceTag(Method): interfaces = Interfaces (self.api, interface_tag['interface_id']) if not interfaces: - raise PLCInvalidArgument, "No such interface %d"%interface_tag['interface_id'] + raise PLCInvalidArgument("No such interface %d"%interface_tag['interface_id']) interface=interfaces[0] # check authorizations diff --git a/PLC/Methods/UpdateKey.py b/PLC/Methods/UpdateKey.py index 870fca75..8163f763 100644 --- a/PLC/Methods/UpdateKey.py +++ b/PLC/Methods/UpdateKey.py @@ -4,7 +4,7 @@ from PLC.Parameter import Parameter, Mixed from PLC.Keys import Key, Keys from PLC.Auth import Auth -can_update = lambda (field, value): field in \ +can_update = lambda field_value: field_value[0] in \ ['key_type', 'key'] class UpdateKey(Method): @@ -19,7 +19,7 @@ class UpdateKey(Method): roles = ['admin', 'pi', 'tech', 'user'] - key_fields = dict(filter(can_update, Key.fields.items())) + key_fields = dict(list(filter(can_update, list(Key.fields.items())))) accepts = [ Auth(), @@ -30,20 +30,20 @@ class UpdateKey(Method): returns = Parameter(int, '1 if successful') def call(self, auth, key_id, key_fields): - key_fields = dict(filter(can_update, key_fields.items())) + key_fields = dict(list(filter(can_update, list(key_fields.items())))) # Get key information keys = Keys(self.api, [key_id]) if not keys: - raise PLCInvalidArgument, "No such key" + raise PLCInvalidArgument("No such key") key = keys[0] if key['peer_id'] is not None: - raise PLCInvalidArgument, "Not a local key" + raise PLCInvalidArgument("Not a local key") if 'admin' not in self.caller['roles']: if key['key_id'] not in self.caller['key_ids']: - raise PLCPermissionDenied, "Key must be associated with one of your accounts" + raise PLCPermissionDenied("Key must be associated with one of your accounts") key.update(key_fields) key.sync() @@ -51,5 +51,5 @@ class UpdateKey(Method): # Logging variables self.event_objects = {'Key': [key['key_id']]} self.message = 'key %d updated: %s' % \ - (key['key_id'], ", ".join(key_fields.keys())) + (key['key_id'], ", ".join(list(key_fields.keys()))) return 1 diff --git a/PLC/Methods/UpdateLeases.py b/PLC/Methods/UpdateLeases.py index c760c5bf..b1c3e1fc 100644 --- a/PLC/Methods/UpdateLeases.py +++ b/PLC/Methods/UpdateLeases.py @@ -1,4 +1,4 @@ -from __future__ import print_function + from PLC.Faults import * from PLC.Method import Method @@ -10,7 +10,7 @@ from PLC.Timestamp import Timestamp, Duration from PLC.Leases import Lease, Leases from PLC.Slices import Slice, Slices -can_update = lambda (field, value): field in ['t_from', 't_until', 'duration'] +can_update = lambda field_value: field_value[0] in ['t_from', 't_until', 'duration'] class UpdateLeases(Method): @@ -29,7 +29,7 @@ class UpdateLeases(Method): roles = ['admin', 'pi', 'tech', 'user'] - lease_fields = dict(filter(can_update, Lease.fields.items())) + lease_fields = dict(list(filter(can_update, list(Lease.fields.items())))) accepts = [ Auth(), @@ -47,7 +47,7 @@ class UpdateLeases(Method): # debug=True def call(self, auth, lease_ids, input_fields): - input_fields = dict(filter(can_update, input_fields.items())) + input_fields = dict(list(filter(can_update, list(input_fields.items())))) if 'duration' in input_fields: if 't_from' in input_fields and 't_until' in input_fields: @@ -126,7 +126,7 @@ class UpdateLeases(Method): lease.update(lease_fields) lease.sync() updated_ids.append(lease['lease_id']) - except Exception, e: + except Exception as e: errors.append( "Could not update lease {} - check new time limits ? -- {}" .format(lease['lease_id'], e)) @@ -134,7 +134,7 @@ class UpdateLeases(Method): # Logging variables self.event_objects = {'Lease': updated_ids} self.message = 'lease {} updated: {}'\ - .format(lease_ids, ", ".join(input_fields.keys())) + .format(lease_ids, ", ".join(list(input_fields.keys()))) return {'updated_ids': updated_ids, 'errors': errors} diff --git a/PLC/Methods/UpdateMessage.py b/PLC/Methods/UpdateMessage.py index 7f961293..dc26f4de 100644 --- a/PLC/Methods/UpdateMessage.py +++ b/PLC/Methods/UpdateMessage.py @@ -4,7 +4,7 @@ from PLC.Parameter import Parameter, Mixed from PLC.Messages import Message, Messages from PLC.Auth import Auth -can_update = lambda (field, value): field in \ +can_update = lambda field_value: field_value[0] in \ ['template', 'enabled'] class UpdateMessage(Method): @@ -17,7 +17,7 @@ class UpdateMessage(Method): roles = ['admin'] - message_fields = dict(filter(can_update, Message.fields.items())) + message_fields = dict(list(filter(can_update, list(Message.fields.items())))) accepts = [ Auth(), @@ -28,12 +28,12 @@ class UpdateMessage(Method): returns = Parameter(int, '1 if successful') def call(self, auth, message_id, message_fields): - message_fields = dict(filter(can_update, message_fields.items())) + message_fields = dict(list(filter(can_update, list(message_fields.items())))) # Get message information messages = Messages(self.api, [message_id]) if not messages: - raise PLCInvalidArgument, "No such message" + raise PLCInvalidArgument("No such message") message = messages[0] message.update(message_fields) diff --git a/PLC/Methods/UpdateNode.py b/PLC/Methods/UpdateNode.py index 973dbb92..df8b0746 100644 --- a/PLC/Methods/UpdateNode.py +++ b/PLC/Methods/UpdateNode.py @@ -48,7 +48,7 @@ class UpdateNode(Method): # type checking native = Row.check_fields (native, self.accepted_fields) if rejected: - raise PLCInvalidArgument, "Cannot update Node column(s) %r"%rejected + raise PLCInvalidArgument("Cannot update Node column(s) %r"%rejected) # Authenticated function assert self.caller is not None @@ -56,26 +56,26 @@ class UpdateNode(Method): # Remove admin only fields if 'admin' not in self.caller['roles']: for key in admin_only: - if native.has_key(key): + if key in native: del native[key] # Get account information nodes = Nodes(self.api, [node_id_or_hostname]) if not nodes: - raise PLCInvalidArgument, "No such node %r"%node_id_or_hostname + raise PLCInvalidArgument("No such node %r"%node_id_or_hostname) node = nodes[0] if node['peer_id'] is not None: - raise PLCInvalidArgument, "Not a local node %r"%node_id_or_hostname + raise PLCInvalidArgument("Not a local node %r"%node_id_or_hostname) # If we are not an admin, make sure that the caller is a # member of the site at which the node is located. if 'admin' not in self.caller['roles']: if node['site_id'] not in self.caller['site_ids']: - raise PLCPermissionDenied, "Not allowed to delete nodes from specified site" + raise PLCPermissionDenied("Not allowed to delete nodes from specified site") # Make requested associations - for (k,v) in related.iteritems(): + for (k,v) in related.items(): node.associate(auth, k,v) node.update(native) @@ -92,11 +92,11 @@ class UpdateNode(Method): login_base = site['login_base'] tags['hrn'] = hostname_to_hrn(root_auth, login_base, node['hostname']) - for (tagname,value) in tags.iteritems(): + for (tagname,value) in tags.items(): # the tagtype instance is assumed to exist, just check that tag_types = TagTypes(self.api,{'tagname':tagname}) if not tag_types: - raise PLCInvalidArgument,"No such TagType %s"%tagname + raise PLCInvalidArgument("No such TagType %s"%tagname) tag_type = tag_types[0] node_tags=NodeTags(self.api,{'tagname':tagname,'node_id':node['node_id']}) if not node_tags: @@ -117,8 +117,8 @@ class UpdateNode(Method): self.message = 'Node %s updated'%node['hostname'] else: self.message = 'Node %d updated'%node['node_id'] - self.message += " [%s]." % (", ".join(node_fields.keys()),) - if 'boot_state' in node_fields.keys(): + self.message += " [%s]." % (", ".join(list(node_fields.keys())),) + if 'boot_state' in list(node_fields.keys()): self.message += ' boot_state updated to %s' % node_fields['boot_state'] return 1 diff --git a/PLC/Methods/UpdateNodeGroup.py b/PLC/Methods/UpdateNodeGroup.py index 6b801875..c867e489 100644 --- a/PLC/Methods/UpdateNodeGroup.py +++ b/PLC/Methods/UpdateNodeGroup.py @@ -4,7 +4,7 @@ from PLC.Parameter import Parameter, Mixed from PLC.NodeGroups import NodeGroup, NodeGroups from PLC.Auth import Auth -can_update = lambda (field, value): field in ['groupname','value'] +can_update = lambda field_value: field_value[0] in ['groupname','value'] class UpdateNodeGroup(Method): """ @@ -15,7 +15,7 @@ class UpdateNodeGroup(Method): roles = ['admin'] - nodegroup_fields = dict(filter(can_update, NodeGroup.fields.items())) + nodegroup_fields = dict(list(filter(can_update, list(NodeGroup.fields.items())))) accepts = [ Auth(), @@ -27,12 +27,12 @@ class UpdateNodeGroup(Method): returns = Parameter(int, '1 if successful') def call(self, auth, nodegroup_id_or_name, nodegroup_fields): - nodegroup_fields = dict(filter(can_update, nodegroup_fields.items())) + nodegroup_fields = dict(list(filter(can_update, list(nodegroup_fields.items())))) # Get nodegroup information nodegroups = NodeGroups(self.api, [nodegroup_id_or_name]) if not nodegroups: - raise PLCInvalidArgument, "No such nodegroup %r"%nodegroup_id_or_name + raise PLCInvalidArgument("No such nodegroup %r"%nodegroup_id_or_name) nodegroup = nodegroups[0] nodegroup.update(nodegroup_fields) @@ -41,5 +41,5 @@ class UpdateNodeGroup(Method): # Logging variables self.event_objects = {'NodeGroup': [nodegroup['nodegroup_id']]} self.message = 'Node group %d updated: %s' % \ - (nodegroup['nodegroup_id'], ", ".join(nodegroup_fields.keys())) + (nodegroup['nodegroup_id'], ", ".join(list(nodegroup_fields.keys()))) return 1 diff --git a/PLC/Methods/UpdateNodeTag.py b/PLC/Methods/UpdateNodeTag.py index d0b3d8e5..55f7348a 100644 --- a/PLC/Methods/UpdateNodeTag.py +++ b/PLC/Methods/UpdateNodeTag.py @@ -39,7 +39,7 @@ class UpdateNodeTag(Method): def call(self, auth, node_tag_id, value): node_tags = NodeTags(self.api, [node_tag_id]) if not node_tags: - raise PLCInvalidArgument, "No such node tag %r"%node_tag_id + raise PLCInvalidArgument("No such node tag %r"%node_tag_id) node_tag = node_tags[0] tag_type_id = node_tag['tag_type_id'] @@ -47,7 +47,7 @@ class UpdateNodeTag(Method): nodes = Nodes (self.api, node_tag['node_id']) if not nodes: - raise PLCInvalidArgument, "No such node %d"%node_tag['node_id'] + raise PLCInvalidArgument("No such node %d"%node_tag['node_id']) node=nodes[0] # check authorizations diff --git a/PLC/Methods/UpdatePCU.py b/PLC/Methods/UpdatePCU.py index fb17176e..84c35730 100644 --- a/PLC/Methods/UpdatePCU.py +++ b/PLC/Methods/UpdatePCU.py @@ -4,7 +4,7 @@ from PLC.Parameter import Parameter, Mixed from PLC.PCUs import PCU, PCUs from PLC.Auth import Auth -can_update = lambda (field, value): field not in \ +can_update = lambda field_value: field_value[0] not in \ ['pcu_id', 'site_id'] class UpdatePCU(Method): @@ -19,7 +19,7 @@ class UpdatePCU(Method): roles = ['admin', 'pi', 'tech'] - update_fields = dict(filter(can_update, PCU.fields.items())) + update_fields = dict(list(filter(can_update, list(PCU.fields.items())))) accepts = [ Auth(), @@ -30,17 +30,17 @@ class UpdatePCU(Method): returns = Parameter(int, '1 if successful') def call(self, auth, pcu_id, pcu_fields): - pcu_fields = dict(filter(can_update, pcu_fields.items())) + pcu_fields = dict(list(filter(can_update, list(pcu_fields.items())))) # Get associated PCU details pcus = PCUs(self.api, [pcu_id]) if not pcus: - raise PLCInvalidArgument, "No such PCU" + raise PLCInvalidArgument("No such PCU") pcu = pcus[0] if 'admin' not in self.caller['roles']: if pcu['site_id'] not in self.caller['site_ids']: - raise PLCPermissionDenied, "Not allowed to update that PCU" + raise PLCPermissionDenied("Not allowed to update that PCU") pcu.update(pcu_fields) pcu.update_last_updated(commit=False) @@ -49,5 +49,5 @@ class UpdatePCU(Method): # Logging variables self.event_objects = {'PCU': [pcu['pcu_id']]} self.message = 'PCU %d updated: %s' % \ - (pcu['pcu_id'], ", ".join(pcu_fields.keys())) + (pcu['pcu_id'], ", ".join(list(pcu_fields.keys()))) return 1 diff --git a/PLC/Methods/UpdatePCUProtocolType.py b/PLC/Methods/UpdatePCUProtocolType.py index b5d915ef..22787e7e 100644 --- a/PLC/Methods/UpdatePCUProtocolType.py +++ b/PLC/Methods/UpdatePCUProtocolType.py @@ -4,7 +4,7 @@ from PLC.Parameter import Parameter, Mixed from PLC.PCUProtocolTypes import PCUProtocolType, PCUProtocolTypes from PLC.Auth import Auth -can_update = lambda (field, value): field in \ +can_update = lambda field_value: field_value[0] in \ ['pcu_type_id', 'port', 'protocol', 'supported'] class UpdatePCUProtocolType(Method): @@ -17,7 +17,7 @@ class UpdatePCUProtocolType(Method): roles = ['admin'] - protocol_type_fields = dict(filter(can_update, PCUProtocolType.fields.items())) + protocol_type_fields = dict(list(filter(can_update, list(PCUProtocolType.fields.items())))) accepts = [ Auth(), @@ -28,11 +28,11 @@ class UpdatePCUProtocolType(Method): returns = Parameter(int, '1 if successful') def call(self, auth, protocol_type_id, protocol_type_fields): - protocol_type_fields = dict(filter(can_update, protocol_type_fields.items())) + protocol_type_fields = dict(list(filter(can_update, list(protocol_type_fields.items())))) protocol_types = PCUProtocolTypes(self.api, [protocol_type_id]) if not protocol_types: - raise PLCInvalidArgument, "No such pcu protocol type" + raise PLCInvalidArgument("No such pcu protocol type") protocol_type = protocol_types[0] protocol_type.update(protocol_type_fields) diff --git a/PLC/Methods/UpdatePCUType.py b/PLC/Methods/UpdatePCUType.py index 2850fdb8..c14006c1 100644 --- a/PLC/Methods/UpdatePCUType.py +++ b/PLC/Methods/UpdatePCUType.py @@ -4,7 +4,7 @@ from PLC.Parameter import Parameter, Mixed from PLC.PCUTypes import PCUType, PCUTypes from PLC.Auth import Auth -can_update = lambda (field, value): field in \ +can_update = lambda field_value: field_value[0] in \ ['model', 'name'] class UpdatePCUType(Method): @@ -17,7 +17,7 @@ class UpdatePCUType(Method): roles = ['admin'] - pcu_type_fields = dict(filter(can_update, PCUType.fields.items())) + pcu_type_fields = dict(list(filter(can_update, list(PCUType.fields.items())))) accepts = [ Auth(), @@ -28,11 +28,11 @@ class UpdatePCUType(Method): returns = Parameter(int, '1 if successful') def call(self, auth, pcu_type_id, pcu_type_fields): - pcu_type_fields = dict(filter(can_update, pcu_type_fields.items())) + pcu_type_fields = dict(list(filter(can_update, list(pcu_type_fields.items())))) pcu_types = PCUTypes(self.api, [pcu_type_id]) if not pcu_types: - raise PLCInvalidArgument, "No such pcu type" + raise PLCInvalidArgument("No such pcu type") pcu_type = pcu_types[0] pcu_type.update(pcu_type_fields) diff --git a/PLC/Methods/UpdatePeer.py b/PLC/Methods/UpdatePeer.py index cd4c1ec5..112ee914 100644 --- a/PLC/Methods/UpdatePeer.py +++ b/PLC/Methods/UpdatePeer.py @@ -4,7 +4,7 @@ from PLC.Parameter import Parameter, Mixed from PLC.Auth import Auth from PLC.Peers import Peer, Peers -can_update = lambda (field, value): field in \ +can_update = lambda field_value: field_value[0] in \ ['peername', 'peer_url', 'key', 'cacert', 'shortname', 'hrn_root'] class UpdatePeer(Method): @@ -17,7 +17,7 @@ class UpdatePeer(Method): roles = ['admin'] - peer_fields = dict(filter(can_update, Peer.fields.items())) + peer_fields = dict(list(filter(can_update, list(Peer.fields.items())))) accepts = [ Auth(), @@ -29,17 +29,17 @@ class UpdatePeer(Method): returns = Parameter(int, "1 if successful") def call(self, auth, peer_id_or_name, peer_fields): - peer_fields = dict(filter(can_update, peer_fields.items())) + peer_fields = dict(list(filter(can_update, list(peer_fields.items())))) # Get account information peers = Peers(self.api, [peer_id_or_name]) if not peers: - raise PLCInvalidArgument, "No such peer" + raise PLCInvalidArgument("No such peer") peer = peers[0] if isinstance(self.caller, Peer): if self.caller['peer_id'] != peer['peer_id']: - raise PLCPermissionDenied, "Not allowed to update specified peer" + raise PLCPermissionDenied("Not allowed to update specified peer") peer.update(peer_fields) peer.sync() diff --git a/PLC/Methods/UpdatePerson.py b/PLC/Methods/UpdatePerson.py index 3212ef5a..f64bb8ce 100644 --- a/PLC/Methods/UpdatePerson.py +++ b/PLC/Methods/UpdatePerson.py @@ -9,7 +9,7 @@ from PLC.TagTypes import TagTypes from PLC.PersonTags import PersonTags, PersonTag from PLC.Namespace import email_to_hrn -related_fields = Person.related_fields.keys() +related_fields = list(Person.related_fields.keys()) can_update = ['first_name', 'last_name', 'title', 'email', 'password', 'phone', 'url', 'bio', 'accepted_aup', 'enabled'] + related_fields @@ -48,7 +48,7 @@ class UpdatePerson(Method): # type checking native = Row.check_fields (native, self.accepted_fields) if rejected: - raise PLCInvalidArgument, "Cannot update Person column(s) %r"%rejected + raise PLCInvalidArgument("Cannot update Person column(s) %r"%rejected) # Authenticated function assert self.caller is not None @@ -56,18 +56,18 @@ class UpdatePerson(Method): # Get account information persons = Persons(self.api, [person_id_or_email]) if not persons: - raise PLCInvalidArgument, "No such account %s"%person_id_or_email + raise PLCInvalidArgument("No such account %s"%person_id_or_email) person = persons[0] if person['peer_id'] is not None: - raise PLCInvalidArgument, "Not a local account %s"%person_id_or_email + raise PLCInvalidArgument("Not a local account %s"%person_id_or_email) # Check if we can update this account if not self.caller.can_update(person): - raise PLCPermissionDenied, "Not allowed to update specified account" + raise PLCPermissionDenied("Not allowed to update specified account") # Make requested associations - for k,v in related.iteritems(): + for k,v in related.items(): person.associate (auth, k, v) person.update(native) @@ -96,11 +96,11 @@ class UpdatePerson(Method): hrn=email_to_hrn("%s.%s"%(root_auth,login_base),person['email']) tags['hrn'] = hrn - for (tagname,value) in tags.iteritems(): + for (tagname,value) in tags.items(): # the tagtype instance is assumed to exist, just check that tag_types = TagTypes(self.api,{'tagname':tagname}) if not tag_types: - raise PLCInvalidArgument,"No such TagType %s"%tagname + raise PLCInvalidArgument("No such TagType %s"%tagname) tag_type = tag_types[0] person_tags=PersonTags(self.api,{'tagname':tagname,'person_id':person['person_id']}) if not person_tags: @@ -122,7 +122,7 @@ class UpdatePerson(Method): if 'password' in person_fields: person_fields['password'] = "Removed by API" self.message = 'Person %d updated: %s.' % \ - (person['person_id'], person_fields.keys()) + (person['person_id'], list(person_fields.keys())) if 'enabled' in person_fields: self.message += ' Person enabled' diff --git a/PLC/Methods/UpdatePersonTag.py b/PLC/Methods/UpdatePersonTag.py index 23ab6ab9..9ebc4947 100644 --- a/PLC/Methods/UpdatePersonTag.py +++ b/PLC/Methods/UpdatePersonTag.py @@ -35,7 +35,7 @@ class UpdatePersonTag(Method): def call(self, auth, person_tag_id, value): person_tags = PersonTags(self.api, [person_tag_id]) if not person_tags: - raise PLCInvalidArgument, "No such person setting %r"%person_tag_id + raise PLCInvalidArgument("No such person setting %r"%person_tag_id) person_tag = person_tags[0] tag_type_id = person_tag['tag_type_id'] @@ -43,7 +43,7 @@ class UpdatePersonTag(Method): persons = Persons (self.api, person_tag['person_id']) if not persons: - raise PLCInvalidArgument, "No such person %d"%person_tag['person_id'] + raise PLCInvalidArgument("No such person %d"%person_tag['person_id']) person=persons[0] # check authorizations diff --git a/PLC/Methods/UpdateSite.py b/PLC/Methods/UpdateSite.py index 86ae121a..8ffbac4f 100644 --- a/PLC/Methods/UpdateSite.py +++ b/PLC/Methods/UpdateSite.py @@ -9,8 +9,8 @@ from PLC.SiteTags import SiteTags from PLC.Methods.AddSiteTag import AddSiteTag from PLC.Methods.UpdateSiteTag import UpdateSiteTag -related_fields = Site.related_fields.keys() -can_update = lambda (field, value): field in \ +related_fields = list(Site.related_fields.keys()) +can_update = lambda field_value: field_value[0] in \ ['name', 'abbreviated_name', 'login_base', 'is_public', 'latitude', 'longitude', 'url', 'max_slices', 'max_slivers', 'enabled', 'ext_consortium_id'] + \ @@ -29,7 +29,7 @@ class UpdateSite(Method): roles = ['admin', 'pi'] - site_fields = dict(filter(can_update, Site.fields.items() + Site.related_fields.items())) + site_fields = dict(list(filter(can_update, list(Site.fields.items()) + list(Site.related_fields.items())))) accepts = [ Auth(), @@ -41,16 +41,16 @@ class UpdateSite(Method): returns = Parameter(int, '1 if successful') def call(self, auth, site_id_or_login_base, site_fields): - site_fields = dict(filter(can_update, site_fields.items())) + site_fields = dict(list(filter(can_update, list(site_fields.items())))) # Get site information sites = Sites(self.api, [site_id_or_login_base]) if not sites: - raise PLCInvalidArgument, "No such site" + raise PLCInvalidArgument("No such site") site = sites[0] if site['peer_id'] is not None: - raise PLCInvalidArgument, "Not a local site" + raise PLCInvalidArgument("Not a local site") # Authenticated function assert self.caller is not None @@ -59,7 +59,7 @@ class UpdateSite(Method): # member of the site. if 'admin' not in self.caller['roles']: if site['site_id'] not in self.caller['site_ids']: - raise PLCPermissionDenied, "Not allowed to modify specified site" + raise PLCPermissionDenied("Not allowed to modify specified site") # Remove admin only fields for key in 'max_slices', 'max_slivers', 'login_base': @@ -79,7 +79,7 @@ class UpdateSite(Method): # Logging variables self.event_objects = {'Site': [site['site_id']]} self.message = 'Site %d updated: %s' % \ - (site['site_id'], ", ".join(site_fields.keys())) + (site['site_id'], ", ".join(list(site_fields.keys()))) # Update Site HRN if login_base changed if 'login_base' in site_fields: diff --git a/PLC/Methods/UpdateSiteTag.py b/PLC/Methods/UpdateSiteTag.py index a5d69f4a..2439fd58 100644 --- a/PLC/Methods/UpdateSiteTag.py +++ b/PLC/Methods/UpdateSiteTag.py @@ -37,7 +37,7 @@ class UpdateSiteTag(Method): def call(self, auth, site_tag_id, value): site_tags = SiteTags(self.api, [site_tag_id]) if not site_tags: - raise PLCInvalidArgument, "No such site setting %r"%site_tag_id + raise PLCInvalidArgument("No such site setting %r"%site_tag_id) site_tag = site_tags[0] tag_type_id = site_tag['tag_type_id'] @@ -45,7 +45,7 @@ class UpdateSiteTag(Method): sites = Sites (self.api, site_tag['site_id']) if not sites: - raise PLCInvalidArgument, "No such site %d"%site_tag['site_id'] + raise PLCInvalidArgument("No such site %d"%site_tag['site_id']) site=sites[0] # check authorizations diff --git a/PLC/Methods/UpdateSlice.py b/PLC/Methods/UpdateSlice.py index 9129ba06..107f0787 100644 --- a/PLC/Methods/UpdateSlice.py +++ b/PLC/Methods/UpdateSlice.py @@ -55,15 +55,15 @@ class UpdateSlice(Method): # type checking native = Row.check_fields (native, self.accepted_fields) if rejected: - raise PLCInvalidArgument, "Cannot update Slice column(s) %r"%rejected + raise PLCInvalidArgument("Cannot update Slice column(s) %r"%rejected) slices = Slices(self.api, [slice_id_or_name]) if not slices: - raise PLCInvalidArgument, "No such slice %r"%slice_id_or_name + raise PLCInvalidArgument("No such slice %r"%slice_id_or_name) slice = slices[0] if slice['peer_id'] is not None: - raise PLCInvalidArgument, "Not a local slice" + raise PLCInvalidArgument("Not a local slice") # Authenticated function assert self.caller is not None @@ -72,9 +72,9 @@ class UpdateSlice(Method): if self.caller['person_id'] in slice['person_ids']: pass elif 'pi' not in self.caller['roles']: - raise PLCPermissionDenied, "Not a member of the specified slice" + raise PLCPermissionDenied("Not a member of the specified slice") elif slice['site_id'] not in self.caller['site_ids']: - raise PLCPermissionDenied, "Specified slice not associated with any of your sites" + raise PLCPermissionDenied("Specified slice not associated with any of your sites") # Renewing renewing=False @@ -84,43 +84,43 @@ class UpdateSlice(Method): site = sites[0] if site['max_slices'] <= 0: - raise PLCInvalidArgument, "Slice creation and renewal have been disabled for the site" + raise PLCInvalidArgument("Slice creation and renewal have been disabled for the site") # Maximum expiration date is 8 weeks from now # XXX Make this configurable max_expires = time.time() + (8 * 7 * 24 * 60 * 60) if 'admin' not in self.caller['roles'] and slice_fields['expires'] > max_expires: - raise PLCInvalidArgument, "Cannot renew a slice beyond 8 weeks from now" + raise PLCInvalidArgument("Cannot renew a slice beyond 8 weeks from now") # XXX Make this a configurable policy if slice['description'] is None or not slice['description'].strip(): if 'description' not in slice_fields or slice_fields['description'] is None or \ not slice_fields['description'].strip(): - raise PLCInvalidArgument, "Cannot renew a slice with an empty description or URL" + raise PLCInvalidArgument("Cannot renew a slice with an empty description or URL") if slice['url'] is None or not slice['url'].strip(): if 'url' not in slice_fields or slice_fields['url'] is None or \ not slice_fields['url'].strip(): - raise PLCInvalidArgument, "Cannot renew a slice with an empty description or URL" + raise PLCInvalidArgument("Cannot renew a slice with an empty description or URL") renewing=True if 'max_nodes' in slice_fields and slice_fields['max_nodes'] != slice['max_nodes']: if 'admin' not in self.caller['roles'] and \ 'pi' not in self.caller['roles']: - raise PLCInvalidArgument, "Only admins and PIs may update max_nodes" + raise PLCInvalidArgument("Only admins and PIs may update max_nodes") # Make requested associations - for (k,v) in related.iteritems(): + for (k,v) in related.items(): slice.associate(auth,k,v) slice.update(slice_fields) slice.sync(commit=True) - for (tagname,value) in tags.iteritems(): + for (tagname,value) in tags.items(): # the tagtype instance is assumed to exist, just check that if not TagTypes(self.api,{'tagname':tagname}): - raise PLCInvalidArgument,"No such TagType %s"%tagname + raise PLCInvalidArgument("No such TagType %s"%tagname) slice_tags=SliceTags(self.api,{'tagname':tagname,'slice_id':slice['slice_id']}) if not slice_tags: AddSliceTag(self.api).__call__(auth,slice['slice_id'],tagname,value) diff --git a/PLC/Methods/UpdateSliceTag.py b/PLC/Methods/UpdateSliceTag.py index 5eff0c37..bbfb33e8 100644 --- a/PLC/Methods/UpdateSliceTag.py +++ b/PLC/Methods/UpdateSliceTag.py @@ -43,7 +43,7 @@ class UpdateSliceTag(Method): def call(self, auth, slice_tag_id, value): slice_tags = SliceTags(self.api, [slice_tag_id]) if not slice_tags: - raise PLCInvalidArgument, "No such slice attribute" + raise PLCInvalidArgument("No such slice attribute") slice_tag = slice_tags[0] tag_type_id = slice_tag['tag_type_id'] @@ -51,7 +51,7 @@ class UpdateSliceTag(Method): slices = Slices(self.api, [slice_tag['slice_id']]) if not slices: - raise PLCInvalidArgument, "No such slice %d"%slice_tag['slice_id'] + raise PLCInvalidArgument("No such slice %d"%slice_tag['slice_id']) slice = slices[0] assert slice_tag['slice_tag_id'] in slice['slice_tag_ids'] @@ -64,9 +64,9 @@ class UpdateSliceTag(Method): if slice_tag['tagname'] in ['initscript']: initscripts = InitScripts(self.api, {'enabled': True, 'name': value}) if not initscripts: - raise PLCInvalidArgument, "No such plc initscript" + raise PLCInvalidArgument("No such plc initscript") - slice_tag['value'] = unicode(value) + slice_tag['value'] = str(value) slice_tag.sync() self.event_objects = {'SliceTag': [slice_tag['slice_tag_id']]} return 1 diff --git a/PLC/Methods/UpdateTagType.py b/PLC/Methods/UpdateTagType.py index 8fc868c2..5f56b2de 100644 --- a/PLC/Methods/UpdateTagType.py +++ b/PLC/Methods/UpdateTagType.py @@ -7,7 +7,7 @@ from PLC.Parameter import Parameter, Mixed from PLC.TagTypes import TagType, TagTypes from PLC.Auth import Auth -can_update = lambda (field, value): field in \ +can_update = lambda field_value: field_value[0] in \ ['tagname', 'description', 'category'] class UpdateTagType(Method): @@ -20,7 +20,7 @@ class UpdateTagType(Method): roles = ['admin'] - tag_type_fields = dict(filter(can_update, TagType.fields.items())) + tag_type_fields = dict(list(filter(can_update, list(TagType.fields.items())))) accepts = [ Auth(), @@ -33,17 +33,17 @@ class UpdateTagType(Method): def call(self, auth, tag_type_id_or_name, tag_type_fields): - accepted_type_fields = dict(filter(can_update, tag_type_fields.items())) + accepted_type_fields = dict(list(filter(can_update, list(tag_type_fields.items())))) rejected_keys = [ k for k in tag_type_fields if k not in accepted_type_fields ] if rejected_keys: error="Cannot update TagType column(s) %r"%rejected_keys if 'roles' in rejected_keys or 'role_ids' in rejected_keys: error += " see AddRoleToTagType DeleteRoleFromTagType" - raise PLCInvalidArgument, error + raise PLCInvalidArgument(error) tag_types = TagTypes(self.api, [tag_type_id_or_name]) if not tag_types: - raise PLCInvalidArgument, "No such tag type" + raise PLCInvalidArgument("No such tag type") tag_type = tag_types[0] tag_type.update(accepted_type_fields) diff --git a/PLC/Methods/VerifyPerson.py b/PLC/Methods/VerifyPerson.py index b34506a1..ef4e988b 100644 --- a/PLC/Methods/VerifyPerson.py +++ b/PLC/Methods/VerifyPerson.py @@ -1,7 +1,7 @@ import random import base64 import time -import urllib +import urllib.request, urllib.parse, urllib.error from PLC.Logger import logger from PLC.Faults import * @@ -46,14 +46,14 @@ class VerifyPerson(Method): # Get account information persons = Persons(self.api, [person_id_or_email]) if not persons: - raise PLCInvalidArgument, "No such account %r"%person_id_or_email + raise PLCInvalidArgument("No such account %r"%person_id_or_email) person = persons[0] if person['peer_id'] is not None: - raise PLCInvalidArgument, "Not a local account %r"%person_id_or_email + raise PLCInvalidArgument("Not a local account %r"%person_id_or_email) if person['enabled']: - raise PLCInvalidArgument, "Account %r must be new (disabled)"%person_id_or_email + raise PLCInvalidArgument("Account %r must be new (disabled)"%person_id_or_email) # Get the primary site name person_sites = Sites(self.api, person['site_ids']) @@ -63,7 +63,7 @@ class VerifyPerson(Method): site_name = "No Site" # Generate 32 random bytes - bytes = random.sample(xrange(0, 256), 32) + bytes = random.sample(range(0, 256), 32) # Base64 encode their string representation random_key = base64.b64encode("".join(map(chr, bytes))) @@ -73,7 +73,7 @@ class VerifyPerson(Method): # Only allow one verification at a time if person['verification_expires'] is not None and \ person['verification_expires'] > time.time(): - raise PLCPermissionDenied, "Verification request already pending" + raise PLCPermissionDenied("Verification request already pending") if verification_expires is None: verification_expires = int(time.time() + (24 * 60 * 60)) @@ -92,9 +92,9 @@ class VerifyPerson(Method): elif verification_key is not None: if person['verification_key'] is None or \ person['verification_expires'] is None: - raise PLCPermissionDenied, "Invalid Verification key" + raise PLCPermissionDenied("Invalid Verification key") elif person['verification_key'] != verification_key: - raise PLCPermissionDenied, "Verification key incorrect" + raise PLCPermissionDenied("Verification key incorrect") else: person['verification_key'] = None person['verification_expires'] = None @@ -105,7 +105,7 @@ class VerifyPerson(Method): for site in person_sites: person_ids.update(site['person_ids']) persons = Persons(self.api, person_ids) - pis = filter(lambda person: 'pi' in person['roles'] and person['enabled'], persons) + pis = [person for person in persons if 'pi' in person['roles'] and person['enabled']] # Send e-mail to PI(s) and copy the user To = [("%s %s" % (pi['first_name'], pi['last_name']), pi['email']) for pi in pis] @@ -130,7 +130,7 @@ class VerifyPerson(Method): 'PLC_WWW_SSL_PORT': self.api.config.PLC_WWW_SSL_PORT, 'person_id': person['person_id'], # Will be used in a URL, so must quote appropriately - 'verification_key': urllib.quote_plus(random_key), + 'verification_key': urllib.parse.quote_plus(random_key), 'site_name': site_name, 'first_name': person['first_name'], 'last_name': person['last_name'], @@ -151,6 +151,6 @@ class VerifyPerson(Method): if verification_key is not None and person['verification_expires'] and \ person['verification_expires'] < time.time(): - raise PLCPermissionDenied, "Verification key has expired. Another email has been sent." + raise PLCPermissionDenied("Verification key has expired. Another email has been sent.") return 1 diff --git a/PLC/Methods/__init__.py b/PLC/Methods/__init__.py index 9b6645bf..27e28b21 100644 --- a/PLC/Methods/__init__.py +++ b/PLC/Methods/__init__.py @@ -1,6 +1,6 @@ #!/usr/bin/python -tt -from __future__ import print_function + import os import glob diff --git a/PLC/Methods/system/methodSignature.py b/PLC/Methods/system/methodSignature.py index 4b049a1d..f73ae93b 100644 --- a/PLC/Methods/system/methodSignature.py +++ b/PLC/Methods/system/methodSignature.py @@ -1,5 +1,6 @@ from PLC.Parameter import Parameter, Mixed from PLC.Method import Method, xmlrpc_type +from functools import reduce class methodSignature(Method): """ diff --git a/PLC/Methods/system/multicall.py b/PLC/Methods/system/multicall.py index 64563ef5..d7fd4113 100644 --- a/PLC/Methods/system/multicall.py +++ b/PLC/Methods/system/multicall.py @@ -1,5 +1,5 @@ import sys -import xmlrpclib +import xmlrpc.client from PLC.Parameter import Parameter, Mixed from PLC.Method import Method @@ -42,13 +42,13 @@ class multicall(Method): params = call['params'] if name == 'system.multicall': errmsg = "Recursive system.multicall forbidden" - raise xmlrpclib.Fault(REQUEST_REFUSED_ERROR, errmsg) + raise xmlrpc.client.Fault(REQUEST_REFUSED_ERROR, errmsg) result = [self.api.call(self.source, name, *params)] - except xmlrpclib.Fault, fault: + except xmlrpc.client.Fault as fault: result = {'faultCode': fault.faultCode, 'faultString': fault.faultString} except: - errmsg = "%s:%s" % (sys.exc_type, sys.exc_value) + errmsg = "%s:%s" % (sys.exc_info()[0], sys.exc_info()[1]) result = {'faultCode': 1, 'faultString': errmsg} results.append(result) return results diff --git a/PLC/NetworkMethods.py b/PLC/NetworkMethods.py index a54934d4..3efd388e 100644 --- a/PLC/NetworkMethods.py +++ b/PLC/NetworkMethods.py @@ -25,12 +25,12 @@ class NetworkMethod(Row): def validate_method(self, name): # Make sure name is not blank if not len(name): - raise PLCInvalidArgument, "Network method must be specified" + raise PLCInvalidArgument("Network method must be specified") # Make sure network method does not alredy exist conflicts = NetworkMethods(self.api, [name]) if conflicts: - raise PLCInvalidArgument, "Network method name already in use" + raise PLCInvalidArgument("Network method name already in use") return name diff --git a/PLC/NetworkTypes.py b/PLC/NetworkTypes.py index eb34e7c9..fd3a30a5 100644 --- a/PLC/NetworkTypes.py +++ b/PLC/NetworkTypes.py @@ -25,12 +25,12 @@ class NetworkType(Row): def validate_type(self, name): # Make sure name is not blank if not len(name): - raise PLCInvalidArgument, "Network type must be specified" + raise PLCInvalidArgument("Network type must be specified") # Make sure network type does not alredy exist conflicts = NetworkTypes(self.api, [name]) if conflicts: - raise PLCInvalidArgument, "Network type name already in use" + raise PLCInvalidArgument("Network type name already in use") return name diff --git a/PLC/NodeGroups.py b/PLC/NodeGroups.py index bbbb6b30..8f0a13ef 100644 --- a/PLC/NodeGroups.py +++ b/PLC/NodeGroups.py @@ -40,13 +40,13 @@ class NodeGroup(Row): def validate_name(self, name): # Make sure name is not blank if not len(name): - raise PLCInvalidArgument, "Invalid node group name" + raise PLCInvalidArgument("Invalid node group name") # Make sure node group does not alredy exist conflicts = NodeGroups(self.api, [name]) for nodegroup in conflicts: if 'nodegroup_id' not in self or self['nodegroup_id'] != nodegroup['nodegroup_id']: - raise PLCInvalidArgument, "Node group name already in use" + raise PLCInvalidArgument("Node group name already in use") return name @@ -91,20 +91,20 @@ class NodeGroups(Table): if nodegroup_filter is not None: if isinstance(nodegroup_filter, (list, tuple, set)): # Separate the list into integers and strings - ints = filter(lambda x: isinstance(x, (int, long)), nodegroup_filter) - strs = filter(lambda x: isinstance(x, StringTypes), nodegroup_filter) + ints = [x for x in nodegroup_filter if isinstance(x, int)] + strs = [x for x in nodegroup_filter if isinstance(x, StringTypes)] nodegroup_filter = Filter(NodeGroup.fields, {'nodegroup_id': ints, 'groupname': strs}) sql += " AND (%s) %s" % nodegroup_filter.sql(api, "OR") elif isinstance(nodegroup_filter, dict): nodegroup_filter = Filter(NodeGroup.fields, nodegroup_filter) sql += " AND (%s) %s" % nodegroup_filter.sql(api, "AND") - elif isinstance(nodegroup_filter, (int, long)): + elif isinstance(nodegroup_filter, int): nodegroup_filter = Filter(NodeGroup.fields, {'nodegroup_id': nodegroup_filter}) sql += " AND (%s) %s" % nodegroup_filter.sql(api, "AND") elif isinstance(nodegroup_filter, StringTypes): nodegroup_filter = Filter(NodeGroup.fields, {'groupname': nodegroup_filter}) sql += " AND (%s) %s" % nodegroup_filter.sql(api, "AND") else: - raise PLCInvalidArgument, "Wrong node group filter %r"%nodegroup_filter + raise PLCInvalidArgument("Wrong node group filter %r"%nodegroup_filter) self.selectall(sql) diff --git a/PLC/NodeTags.py b/PLC/NodeTags.py index 7f69e325..adbc1686 100644 --- a/PLC/NodeTags.py +++ b/PLC/NodeTags.py @@ -40,12 +40,12 @@ class NodeTags(Table): ", ".join(self.columns) if node_tag_filter is not None: - if isinstance(node_tag_filter, (list, tuple, set, int, long)): + if isinstance(node_tag_filter, (list, tuple, set, int)): node_tag_filter = Filter(NodeTag.fields, {'node_tag_id': node_tag_filter}) elif isinstance(node_tag_filter, dict): node_tag_filter = Filter(NodeTag.fields, node_tag_filter) else: - raise PLCInvalidArgument, "Wrong node tag filter %r"%node_tag_filter + raise PLCInvalidArgument("Wrong node tag filter %r"%node_tag_filter) sql += " AND (%s) %s" % node_tag_filter.sql(api) diff --git a/PLC/NodeTypes.py b/PLC/NodeTypes.py index 00d4bf71..3ae75a64 100644 --- a/PLC/NodeTypes.py +++ b/PLC/NodeTypes.py @@ -23,12 +23,12 @@ class NodeType(Row): def validate_node_type(self, name): # Make sure name is not blank if not len(name): - raise PLCInvalidArgument, "Node type must be specified" + raise PLCInvalidArgument("Node type must be specified") # Make sure node type does not alredy exist conflicts = NodeTypes(self.api, [name]) if conflicts: - raise PLCInvalidArgument, "Node type name already in use" + raise PLCInvalidArgument("Node type name already in use") return name diff --git a/PLC/Nodes.py b/PLC/Nodes.py index 7e27ed44..efef4c1c 100644 --- a/PLC/Nodes.py +++ b/PLC/Nodes.py @@ -94,25 +94,25 @@ class Node(Row): def validate_hostname(self, hostname): hostname = hostname.lower() if not valid_hostname(hostname): - raise PLCInvalidArgument, "Invalid hostname" + raise PLCInvalidArgument("Invalid hostname") conflicts = Nodes(self.api, [hostname]) for node in conflicts: if 'node_id' not in self or self['node_id'] != node['node_id']: - raise PLCInvalidArgument, "Hostname already in use" + raise PLCInvalidArgument("Hostname already in use") return hostname def validate_node_type(self, node_type): node_types = [row['node_type'] for row in NodeTypes(self.api)] if node_type not in node_types: - raise PLCInvalidArgument, "Invalid node type %r"%node_type + raise PLCInvalidArgument("Invalid node type %r"%node_type) return node_type def validate_boot_state(self, boot_state): boot_states = [row['boot_state'] for row in BootStates(self.api)] if boot_state not in boot_states: - raise PLCInvalidArgument, "Invalid boot state %r"%boot_state + raise PLCInvalidArgument("Invalid boot state %r"%boot_state) return boot_state validate_date_created = Row.validate_timestamp @@ -164,10 +164,10 @@ class Node(Row): from PLC.Methods.AddNodeTag import AddNodeTag from PLC.Methods.UpdateNodeTag import UpdateNodeTag shell = Shell() - for (tagname,value) in tags.iteritems(): + for (tagname,value) in tags.items(): # the tagtype instance is assumed to exist, just check that if not TagTypes(self.api,{'tagname':tagname}): - raise PLCInvalidArgument,"No such TagType %s"%tagname + raise PLCInvalidArgument("No such TagType %s"%tagname) node_tags=NodeTags(self.api,{'tagname':tagname,'node_id':node['node_id']}) if not node_tags: AddNodeTag(self.api).__call__(shell.auth,node['node_id'],tagname,value) @@ -234,7 +234,7 @@ class Node(Row): if slice_names: slices = Slices(self.api, slice_names, ['slice_id']).dict('slice_id') - slice_ids += slices.keys() + slice_ids += list(slices.keys()) if self['slice_ids'] != slice_ids: from PLC.Methods.AddSliceToNodes import AddSliceToNodes @@ -263,7 +263,7 @@ class Node(Row): if slice_names: slices = Slices(self.api, slice_names, ['slice_id']).dict('slice_id') - slice_ids += slices.keys() + slice_ids += list(slices.keys()) if self['slice_ids_whitelist'] != slice_ids: from PLC.Methods.AddSliceToNodesWhitelist import AddSliceToNodesWhitelist @@ -319,26 +319,26 @@ class Nodes(Table): Node.primary_key) sql = "SELECT %s FROM %s WHERE deleted IS False" % \ - (", ".join(self.columns.keys()+self.tag_columns.keys()),view) + (", ".join(list(self.columns.keys())+list(self.tag_columns.keys())),view) if node_filter is not None: if isinstance(node_filter, (list, tuple, set)): # Separate the list into integers and strings - ints = filter(lambda x: isinstance(x, (int, long)), node_filter) - strs = filter(lambda x: isinstance(x, StringTypes), node_filter) + ints = [x for x in node_filter if isinstance(x, int)] + strs = [x for x in node_filter if isinstance(x, StringTypes)] node_filter = Filter(Node.fields, {'node_id': ints, 'hostname': strs}) sql += " AND (%s) %s" % node_filter.sql(api, "OR") elif isinstance(node_filter, dict): - allowed_fields=dict(Node.fields.items()+Node.tags.items()) + allowed_fields=dict(list(Node.fields.items())+list(Node.tags.items())) node_filter = Filter(allowed_fields, node_filter) sql += " AND (%s) %s" % node_filter.sql(api, "AND") elif isinstance (node_filter, StringTypes): node_filter = Filter(Node.fields, {'hostname':node_filter}) sql += " AND (%s) %s" % node_filter.sql(api, "AND") - elif isinstance (node_filter, (int, long)): + elif isinstance (node_filter, int): node_filter = Filter(Node.fields, {'node_id':node_filter}) sql += " AND (%s) %s" % node_filter.sql(api, "AND") else: - raise PLCInvalidArgument, "Wrong node filter %r"%node_filter + raise PLCInvalidArgument("Wrong node filter %r"%node_filter) self.selectall(sql) diff --git a/PLC/PCUProtocolTypes.py b/PLC/PCUProtocolTypes.py index 9281c46a..d0d92509 100644 --- a/PLC/PCUProtocolTypes.py +++ b/PLC/PCUProtocolTypes.py @@ -31,14 +31,14 @@ class PCUProtocolType(Row): # make sure port is not blank if not port: - raise PLCInvalidArgument, "Port must be specified" + raise PLCInvalidArgument("Port must be specified") return port def validate_protocol(self, protocol): # make sure port is not blank if not len(protocol): - raise PLCInvalidArgument, "protocol must be specified" + raise PLCInvalidArgument("protocol must be specified") return protocol @@ -54,14 +54,14 @@ class PCUProtocolTypes(Table): ", ".join(self.columns) if protocol_type_filter is not None: - if isinstance(protocol_type_filter, (list, tuple, set, int, long)): + if isinstance(protocol_type_filter, (list, tuple, set, int)): protocol_type_filter = Filter(PCUProtocolType.fields, {'pcu_protocol_type_id': protocol_type_filter}) sql += " AND (%s) %s" % protocol_type_filter.sql(api, "OR") elif isinstance(protocol_type_filter, dict): protocol_type_filter = Filter(PCUProtocolType.fields, protocol_type_filter) sql += " AND (%s) %s" % protocol_type_filter.sql(api, "AND") else: - raise PLCInvalidArgument, "Wrong pcu_protocol_type filter %r"%protocol_type_filter + raise PLCInvalidArgument("Wrong pcu_protocol_type filter %r"%protocol_type_filter) self.selectall(sql) diff --git a/PLC/PCUTypes.py b/PLC/PCUTypes.py index 78a33536..50177d5f 100644 --- a/PLC/PCUTypes.py +++ b/PLC/PCUTypes.py @@ -32,13 +32,13 @@ class PCUType(Row): def validate_model(self, model): # Make sure name is not blank if not len(model): - raise PLCInvalidArgument, "Model must be specified" + raise PLCInvalidArgument("Model must be specified") # Make sure boot state does not alredy exist conflicts = PCUTypes(self.api, [model]) for pcu_type in conflicts: if 'pcu_type_id' not in self or self['pcu_type_id'] != pcu_type['pcu_type_id']: - raise PLCInvalidArgument, "Model already in use" + raise PLCInvalidArgument("Model already in use") return model @@ -52,7 +52,7 @@ class PCUTypes(Table): # Remove pcu_protocol_types from query since its not really a field # in the db. We will add it later if columns == None: - columns = PCUType.fields.keys() + columns = list(PCUType.fields.keys()) if 'pcu_protocol_types' in columns: removed_fields = ['pcu_protocol_types'] columns.remove('pcu_protocol_types') @@ -67,8 +67,8 @@ class PCUTypes(Table): if pcu_type_filter is not None: if isinstance(pcu_type_filter, (list, tuple, set)): # Separate the list into integers and strings - ints = filter(lambda x: isinstance(x, (int, long)), pcu_type_filter) - strs = filter(lambda x: isinstance(x, StringTypes), pcu_type_filter) + ints = [x for x in pcu_type_filter if isinstance(x, int)] + strs = [x for x in pcu_type_filter if isinstance(x, StringTypes)] pcu_type_filter = Filter(PCUType.fields, {'pcu_type_id': ints, 'model': strs}) sql += " AND (%s) %s" % pcu_type_filter.sql(api, "OR") elif isinstance(pcu_type_filter, dict): @@ -81,7 +81,7 @@ class PCUTypes(Table): pcu_type_filter = Filter(PCUType.fields, {'pcu_type_id':pcu_type_filter}) sql += " AND (%s) %s" % pcu_type_filter.sql(api, "AND") else: - raise PLCInvalidArgument, "Wrong pcu_type filter %r"%pcu_type_filter + raise PLCInvalidArgument("Wrong pcu_type filter %r"%pcu_type_filter) self.selectall(sql) diff --git a/PLC/PCUs.py b/PLC/PCUs.py index d628677b..b1ad003a 100644 --- a/PLC/PCUs.py +++ b/PLC/PCUs.py @@ -39,7 +39,7 @@ class PCU(Row): def validate_ip(self, ip): if not valid_ip(ip): - raise PLCInvalidArgument, "Invalid IP address " + ip + raise PLCInvalidArgument("Invalid IP address " + ip) return ip validate_last_updated = Row.validate_timestamp @@ -66,7 +66,7 @@ class PCU(Row): assert 'pcu_id' in self assert isinstance(node, Node) - assert isinstance(port, (int, long)) + assert isinstance(port, int) assert 'node_id' in node pcu_id = self['pcu_id'] @@ -123,12 +123,12 @@ class PCUs(Table): ", ".join(self.columns) if pcu_filter is not None: - if isinstance(pcu_filter, (list, tuple, set, int, long)): + if isinstance(pcu_filter, (list, tuple, set, int)): pcu_filter = Filter(PCU.fields, {'pcu_id': pcu_filter}) elif isinstance(pcu_filter, dict): pcu_filter = Filter(PCU.fields, pcu_filter) else: - raise PLCInvalidArgument, "Wrong pcu filter %r"%pcu_filter + raise PLCInvalidArgument("Wrong pcu filter %r"%pcu_filter) sql += " AND (%s) %s" % pcu_filter.sql(api) self.selectall(sql) diff --git a/PLC/POD.py b/PLC/POD.py index 41227d2b..a5eddfd3 100644 --- a/PLC/POD.py +++ b/PLC/POD.py @@ -66,14 +66,14 @@ def _construct(id, data): def icmp_pod(host,key): uid = os.getuid() - if uid <> 0: - print "must be root to send icmp pod" + if uid != 0: + print("must be root to send icmp pod") return s = socket(AF_INET, SOCK_RAW, getprotobyname("icmp")) packet = _construct(0, key) # make a ping packet addr = (host,1) - print 'pod sending icmp-based reboot request to %s' % host + print('pod sending icmp-based reboot request to %s' % host) for i in range(1,10): s.sendto(packet, addr) @@ -82,7 +82,7 @@ def udp_pod(host,key,fromaddr=('', 0)): s = socket(AF_INET, SOCK_DGRAM) s.bind(fromaddr) packet = key - print 'pod sending udp-based reboot request to %s' % host + print('pod sending udp-based reboot request to %s' % host) for i in range(1,10): s.sendto(packet, addr) diff --git a/PLC/Parameter.py b/PLC/Parameter.py index 6268fcec..08352ffd 100644 --- a/PLC/Parameter.py +++ b/PLC/Parameter.py @@ -99,4 +99,4 @@ def xmlrpc_type(arg): # documentation purposes. return "mixed" else: - raise PLCAPIError, "XML-RPC cannot marshal %s objects" % arg_type + raise PLCAPIError("XML-RPC cannot marshal %s objects" % arg_type) diff --git a/PLC/Peers.py b/PLC/Peers.py index c272a2ac..5b24ca23 100644 --- a/PLC/Peers.py +++ b/PLC/Peers.py @@ -5,7 +5,7 @@ import re from types import StringTypes import traceback -from urlparse import urlparse +from urllib.parse import urlparse import PLC.Auth from PLC.Logger import logger @@ -50,12 +50,12 @@ class Peer(Row): def validate_peername(self, peername): if not len(peername): - raise PLCInvalidArgument, "Peer name must be specified" + raise PLCInvalidArgument("Peer name must be specified") conflicts = Peers(self.api, [peername]) for peer in conflicts: if 'peer_id' not in self or self['peer_id'] != peer['peer_id']: - raise PLCInvalidArgument, "Peer name already in use" + raise PLCInvalidArgument("Peer name already in use") return peername @@ -66,9 +66,9 @@ class Peer(Row): (scheme, netloc, path, params, query, fragment) = urlparse(url) if scheme != "https": - raise PLCInvalidArgument, "Peer URL scheme must be https" + raise PLCInvalidArgument("Peer URL scheme must be https") if path[-1] != '/': - raise PLCInvalidArgument, "Peer URL should end with /" + raise PLCInvalidArgument("Peer URL should end with /") return url @@ -218,9 +218,9 @@ class Peer(Row): Connect to this peer via XML-RPC. """ - import xmlrpclib + import xmlrpc.client from PLC.PyCurl import PyCurlTransport - self.server = xmlrpclib.ServerProxy(self['peer_url'], + self.server = xmlrpc.client.ServerProxy(self['peer_url'], PyCurlTransport(self['peer_url'], self['cacert']), allow_none = 1, **kwds) @@ -265,16 +265,16 @@ class Peer(Row): if api_function.accepts and \ (isinstance(api_function.accepts[0], PLC.Auth.Auth) or \ (isinstance(api_function.accepts[0], Mixed) and \ - filter(lambda param: isinstance(param, Auth), api_function.accepts[0]))): + [param for param in api_function.accepts[0] if isinstance(param, Auth)])): function = getattr(self.server, methodname) return self.add_auth(function, methodname) - except Exception, err: + except Exception as err: pass if hasattr(self, attr): return getattr(self, attr) else: - raise AttributeError, "type object 'Peer' has no attribute '%s'" % attr + raise AttributeError("type object 'Peer' has no attribute '%s'" % attr) class Peers (Table): """ @@ -290,20 +290,20 @@ class Peers (Table): if peer_filter is not None: if isinstance(peer_filter, (list, tuple, set)): # Separate the list into integers and strings - ints = filter(lambda x: isinstance(x, (int, long)), peer_filter) - strs = filter(lambda x: isinstance(x, StringTypes), peer_filter) + ints = [x for x in peer_filter if isinstance(x, int)] + strs = [x for x in peer_filter if isinstance(x, StringTypes)] peer_filter = Filter(Peer.fields, {'peer_id': ints, 'peername': strs}) sql += " AND (%s) %s" % peer_filter.sql(api, "OR") elif isinstance(peer_filter, dict): peer_filter = Filter(Peer.fields, peer_filter) sql += " AND (%s) %s" % peer_filter.sql(api, "AND") - elif isinstance(peer_filter, (int, long)): + elif isinstance(peer_filter, int): peer_filter = Filter(Peer.fields, {'peer_id': peer_filter}) sql += " AND (%s) %s" % peer_filter.sql(api, "AND") elif isinstance(peer_filter, StringTypes): peer_filter = Filter(Peer.fields, {'peername': peer_filter}) sql += " AND (%s) %s" % peer_filter.sql(api, "AND") else: - raise PLCInvalidArgument, "Wrong peer filter %r"%peer_filter + raise PLCInvalidArgument("Wrong peer filter %r"%peer_filter) self.selectall(sql) diff --git a/PLC/PersonTags.py b/PLC/PersonTags.py index 9327abf3..a0f83332 100644 --- a/PLC/PersonTags.py +++ b/PLC/PersonTags.py @@ -42,12 +42,12 @@ class PersonTags(Table): ", ".join(self.columns) if person_tag_filter is not None: - if isinstance(person_tag_filter, (list, tuple, set, int, long)): + if isinstance(person_tag_filter, (list, tuple, set, int)): person_tag_filter = Filter(PersonTag.fields, {'person_tag_id': person_tag_filter}) elif isinstance(person_tag_filter, dict): person_tag_filter = Filter(PersonTag.fields, person_tag_filter) else: - raise PLCInvalidArgument, "Wrong person setting filter %r"%person_tag_filter + raise PLCInvalidArgument("Wrong person setting filter %r"%person_tag_filter) sql += " AND (%s) %s" % person_tag_filter.sql(api) diff --git a/PLC/Persons.py b/PLC/Persons.py index 8cd2856a..30bdcfca 100644 --- a/PLC/Persons.py +++ b/PLC/Persons.py @@ -96,7 +96,7 @@ class Person(Row): for person in conflicts: if 'person_id' not in self or self['person_id'] != person['person_id']: - raise PLCInvalidArgument, "E-mail address already in use" + raise PLCInvalidArgument("E-mail address already in use") return email @@ -230,7 +230,7 @@ class Person(Row): # Translate roles into role_ids if role_names: roles = Roles(self.api, role_names).dict('role_id') - role_ids += roles.keys() + role_ids += list(roles.keys()) # Add new ids, remove stale ids if self['role_ids'] != role_ids: @@ -262,7 +262,7 @@ class Person(Row): # Translate roles into role_ids if site_names: sites = Sites(self.api, site_names, ['site_id']).dict('site_id') - site_ids += sites.keys() + site_ids += list(sites.keys()) # Add new ids, remove stale ids if self['site_ids'] != site_ids: @@ -299,8 +299,8 @@ class Person(Row): if keys: from PLC.Methods.AddPersonKey import AddPersonKey from PLC.Methods.UpdateKey import UpdateKey - updated_keys = filter(lambda key: 'key_id' in key, keys) - added_keys = filter(lambda key: 'key_id' not in key, keys) + updated_keys = [key for key in keys if 'key_id' in key] + added_keys = [key for key in keys if 'key_id' not in key] for key in added_keys: AddPersonKey.__call__(AddPersonKey(self.api), auth, self['person_id'], key) @@ -326,7 +326,7 @@ class Person(Row): # Translate roles into role_ids if slice_names: slices = Slices(self.api, slice_names, ['slice_id']).dict('slice_id') - slice_ids += slices.keys() + slice_ids += list(slices.keys()) # Add new ids, remove stale ids if self['slice_ids'] != slice_ids: @@ -382,26 +382,26 @@ class Persons(Table): Person.primary_key) sql = "SELECT %s FROM %s WHERE deleted IS False" % \ - (", ".join(self.columns.keys()+self.tag_columns.keys()),view) + (", ".join(list(self.columns.keys())+list(self.tag_columns.keys())),view) if person_filter is not None: if isinstance(person_filter, (list, tuple, set)): # Separate the list into integers and strings - ints = filter(lambda x: isinstance(x, (int, long)), person_filter) - strs = filter(lambda x: isinstance(x, StringTypes), person_filter) + ints = [x for x in person_filter if isinstance(x, int)] + strs = [x for x in person_filter if isinstance(x, StringTypes)] person_filter = Filter(Person.fields, {'person_id': ints, 'email': strs}) sql += " AND (%s) %s" % person_filter.sql(api, "OR") elif isinstance(person_filter, dict): - allowed_fields=dict(Person.fields.items()+Person.tags.items()) + allowed_fields=dict(list(Person.fields.items())+list(Person.tags.items())) person_filter = Filter(allowed_fields, person_filter) sql += " AND (%s) %s" % person_filter.sql(api, "AND") elif isinstance (person_filter, StringTypes): person_filter = Filter(Person.fields, {'email':person_filter}) sql += " AND (%s) %s" % person_filter.sql(api, "AND") - elif isinstance (person_filter, (int, long)): + elif isinstance (person_filter, int): person_filter = Filter(Person.fields, {'person_id':person_filter}) sql += " AND (%s) %s" % person_filter.sql(api, "AND") else: - raise PLCInvalidArgument, "Wrong person filter %r"%person_filter + raise PLCInvalidArgument("Wrong person filter %r"%person_filter) self.selectall(sql) diff --git a/PLC/PostgreSQL.py b/PLC/PostgreSQL.py index e04b02be..27a8ab4f 100644 --- a/PLC/PostgreSQL.py +++ b/PLC/PostgreSQL.py @@ -15,7 +15,7 @@ psycopg2.extensions.register_type(psycopg2._psycopg.UNICODEARRAY) import types from types import StringTypes, NoneType import traceback -import commands +import subprocess import re from pprint import pformat @@ -63,21 +63,21 @@ class PostgreSQL: def _quote(x): if isinstance(x, DateTimeType): x = str(x) - elif isinstance(x, unicode): + elif isinstance(x, str): x = x.encode( 'utf-8' ) - if isinstance(x, types.StringType): + if isinstance(x, bytes): x = "'%s'" % str(x).replace("\\", "\\\\").replace("'", "''") - elif isinstance(x, (types.IntType, types.LongType, types.FloatType)): + elif isinstance(x, (int, float)): pass elif x is None: x = 'NULL' - elif isinstance(x, (types.ListType, types.TupleType, set)): - x = 'ARRAY[%s]' % ', '.join(map(lambda x: str(_quote(x)), x)) + elif isinstance(x, (list, tuple, set)): + x = 'ARRAY[%s]' % ', '.join([str(_quote(x)) for x in x]) elif hasattr(x, '__pg_repr__'): x = x.__pg_repr__() else: - raise PLCDBError, 'Cannot quote type %s' % type(x) + raise PLCDBError('Cannot quote type %s' % type(x)) return x @@ -195,12 +195,12 @@ class PostgreSQL: cursor.executemany(query, param_seq) (self.rowcount, self.description, self.lastrowid) = \ (cursor.rowcount, cursor.description, cursor.lastrowid) - except Exception, e: + except Exception as e: try: self.rollback() except: pass - uuid = commands.getoutput("uuidgen") + uuid = subprocess.getoutput("uuidgen") message = "Database error {}: - Query {} - Params {}".format(uuid, query, pformat(params)) logger.exception(message) raise PLCDBError("Please contact " + \ @@ -229,7 +229,7 @@ class PostgreSQL: # Return each row as a dictionary keyed on field name # (like DBI selectrow_hashref()). labels = [column[0] for column in self.description] - rows = [dict(zip(labels, row)) for row in rows] + rows = [dict(list(zip(labels, row))) for row in rows] if key_field is not None and key_field in labels: # Return rows as a dictionary keyed on the specified field @@ -244,7 +244,7 @@ class PostgreSQL: """ if hasattr(self, 'fields_cache'): - if self.fields_cache.has_key((table, notnull, hasdef)): + if (table, notnull, hasdef) in self.fields_cache: return self.fields_cache[(table, notnull, hasdef)] else: self.fields_cache = {} diff --git a/PLC/PyCurl.py b/PLC/PyCurl.py index 4ae2fdc9..44fd685f 100644 --- a/PLC/PyCurl.py +++ b/PLC/PyCurl.py @@ -7,14 +7,14 @@ # import os -import xmlrpclib -import pycurl +import xmlrpc.client +from . import pycurl from tempfile import NamedTemporaryFile -class PyCurlTransport(xmlrpclib.Transport): +class PyCurlTransport(xmlrpc.client.Transport): def __init__(self, uri, cert = None, timeout = 300): - if hasattr(xmlrpclib.Transport,'__init__'): - xmlrpclib.Transport.__init__(self) + if hasattr(xmlrpc.client.Transport,'__init__'): + xmlrpc.client.Transport.__init__(self) self.curl = pycurl.Curl() # Suppress signals @@ -65,13 +65,13 @@ class PyCurlTransport(xmlrpclib.Transport): response = self.body self.body = "" errmsg="" - except pycurl.error, err: + except pycurl.error as err: (errcode, errmsg) = err if errcode == 60: - raise Exception, "PyCurl: SSL certificate validation failed" + raise Exception("PyCurl: SSL certificate validation failed") elif errcode != 200: - raise Exception, "PyCurl: HTTP error %d -- %r" % (errcode,errmsg) + raise Exception("PyCurl: HTTP error %d -- %r" % (errcode,errmsg)) # Parse response p, u = self.getparser() diff --git a/PLC/Roles.py b/PLC/Roles.py index fcc05f4b..283b386b 100644 --- a/PLC/Roles.py +++ b/PLC/Roles.py @@ -29,19 +29,19 @@ class Role(Row): # Make sure role does not already exist conflicts = Roles(self.api, [role_id]) if conflicts: - raise PLCInvalidArgument, "Role ID already in use" + raise PLCInvalidArgument("Role ID already in use") return role_id def validate_name(self, name): # Make sure name is not blank if not len(name): - raise PLCInvalidArgument, "Role must be specified" + raise PLCInvalidArgument("Role must be specified") # Make sure role does not already exist conflicts = Roles(self.api, [name]) if conflicts: - raise PLCInvalidArgument, "Role name already in use" + raise PLCInvalidArgument("Role name already in use") return name @@ -59,20 +59,20 @@ class Roles(Table): if role_filter is not None: if isinstance(role_filter, (list, tuple, set)): # Separate the list into integers and strings - ints = filter(lambda x: isinstance(x, (int, long)), role_filter) - strs = filter(lambda x: isinstance(x, StringTypes), role_filter) + ints = [x for x in role_filter if isinstance(x, int)] + strs = [x for x in role_filter if isinstance(x, StringTypes)] role_filter = Filter(Role.fields, {'role_id': ints, 'name': strs}) sql += " AND (%s) %s" % role_filter.sql(api, "OR") elif isinstance(role_filter, dict): role_filter = Filter(Role.fields, role_filter) sql += " AND (%s) %s" % role_filter.sql(api, "AND") - elif isinstance(role_filter, (int, long)): + elif isinstance(role_filter, int): role_filter = Filter(Role.fields, {'role_id': role_filter}) sql += " AND (%s) %s" % role_filter.sql(api, "AND") elif isinstance(role_filter, StringTypes): role_filter = Filter(Role.fields, {'name': role_filter}) sql += " AND (%s) %s" % role_filter.sql(api, "AND") else: - raise PLCInvalidArgument, "Wrong role filter %r"%role_filter + raise PLCInvalidArgument("Wrong role filter %r"%role_filter) self.selectall(sql) diff --git a/PLC/Sessions.py b/PLC/Sessions.py index 6a03068b..24ed8ad4 100644 --- a/PLC/Sessions.py +++ b/PLC/Sessions.py @@ -29,7 +29,7 @@ class Session(Row): def validate_expires(self, expires): if expires < time.time(): - raise PLCInvalidArgument, "Expiration date must be in the future" + raise PLCInvalidArgument("Expiration date must be in the future") return time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(expires)) @@ -44,14 +44,14 @@ class Session(Row): add(self, node, commit = commit) def sync(self, commit = True, insert = None): - if not self.has_key('session_id'): + if 'session_id' not in self: # Before a new session is added, delete expired sessions expired = Sessions(self.api, expires = -int(time.time())) for session in expired: session.delete(commit) # Generate 32 random bytes - bytes = random.sample(xrange(0, 256), 32) + bytes = random.sample(range(0, 256), 32) # Base64 encode their string representation self['session_id'] = base64.b64encode("".join(map(chr, bytes))) # Force insert @@ -73,21 +73,21 @@ class Sessions(Table): if session_filter is not None: if isinstance(session_filter, (list, tuple, set)): # Separate the list into integers and strings - ints = filter(lambda x: isinstance(x, (int, long)), session_filter) - strs = filter(lambda x: isinstance(x, StringTypes), session_filter) + ints = [x for x in session_filter if isinstance(x, int)] + strs = [x for x in session_filter if isinstance(x, StringTypes)] session_filter = Filter(Session.fields, {'person_id': ints, 'session_id': strs}) sql += " AND (%s) %s" % session_filter.sql(api, "OR") elif isinstance(session_filter, dict): session_filter = Filter(Session.fields, session_filter) sql += " AND (%s) %s" % session_filter.sql(api, "AND") - elif isinstance(session_filter, (int, long)): + elif isinstance(session_filter, int): session_filter = Filter(Session.fields, {'person_id': session_filter}) sql += " AND (%s) %s" % session_filter.sql(api, "AND") elif isinstance(session_filter, StringTypes): session_filter = Filter(Session.fields, {'session_id': session_filter}) sql += " AND (%s) %s" % session_filter.sql(api, "AND") else: - raise PLCInvalidArgument, "Wrong session filter"%session_filter + raise PLCInvalidArgument("Wrong session filter"%session_filter) if expires is not None: if expires >= 0: diff --git a/PLC/Shell.py b/PLC/Shell.py index df87e1cc..48602f7e 100644 --- a/PLC/Shell.py +++ b/PLC/Shell.py @@ -8,7 +8,7 @@ import os import pydoc -import xmlrpclib +import xmlrpc.client from PLC.API import PLCAPI from PLC.Parameter import Mixed @@ -38,8 +38,8 @@ class Callable: if self.auth and \ (not args or not isinstance(args[0], dict) or \ - (not args[0].has_key('AuthMethod') and \ - not args[0].has_key('session'))): + ('AuthMethod' not in args[0] and \ + 'session' not in args[0])): args = (self.auth,) + args if self.shell.multi: @@ -85,7 +85,7 @@ class Shell: self.config = self.api.config self.url = None self.server = None - except Exception, err: + except Exception as err: # Try connecting to the API server via XML-RPC self.api = PLCAPI(None) @@ -94,13 +94,13 @@ class Shell: self.config = Config() else: self.config = Config(config) - except Exception, err: + except Exception as err: # Try to continue if no configuration file is available self.config = None if url is None: if self.config is None: - raise Exception, "Must specify API URL" + raise Exception("Must specify API URL") url = "https://" + self.config.PLC_API_HOST + \ ":" + str(self.config.PLC_API_PORT) + \ @@ -111,9 +111,9 @@ class Shell: self.url = url if cacert is not None: - self.server = xmlrpclib.ServerProxy(url, PyCurlTransport(url, cacert), allow_none = 1) + self.server = xmlrpc.client.ServerProxy(url, PyCurlTransport(url, cacert), allow_none = 1) else: - self.server = xmlrpclib.ServerProxy(url, allow_none = 1) + self.server = xmlrpc.client.ServerProxy(url, allow_none = 1) # Set up authentication structure @@ -143,7 +143,7 @@ class Shell: self.auth = {'AuthMethod': "anonymous"} elif method == "session": if session is None: - raise Exception, "Must specify session" + raise Exception("Must specify session") if os.path.exists(session): session = file(session).read() @@ -151,10 +151,10 @@ class Shell: self.auth = {'AuthMethod': "session", 'session': session} else: if user is None: - raise Exception, "Must specify username" + raise Exception("Must specify username") if password is None: - raise Exception, "Must specify password" + raise Exception("Must specify password") self.auth = {'AuthMethod': method, 'Username': user, @@ -178,7 +178,7 @@ class Shell: if api_function.accepts and \ (isinstance(api_function.accepts[0], Auth) or \ (isinstance(api_function.accepts[0], Mixed) and \ - filter(lambda param: isinstance(param, Auth), api_function.accepts[0]))): + [param for param in api_function.accepts[0] if isinstance(param, Auth)])): auth = self.auth else: auth = None @@ -233,7 +233,7 @@ class Shell: def begin(self): if self.calls: - raise Exception, "multicall already in progress" + raise Exception("multicall already in progress") self.multi = True @@ -244,11 +244,11 @@ class Shell: results = self.system.multicall(self.calls) for result in results: if type(result) == type({}): - raise xmlrpclib.Fault(result['faultCode'], result['faultString']) + raise xmlrpc.client.Fault(result['faultCode'], result['faultString']) elif type(result) == type([]): ret.append(result[0]) else: - raise ValueError, "unexpected type in multicall result" + raise ValueError("unexpected type in multicall result") else: ret = None diff --git a/PLC/SiteTags.py b/PLC/SiteTags.py index d04b9475..a03ac24a 100644 --- a/PLC/SiteTags.py +++ b/PLC/SiteTags.py @@ -42,12 +42,12 @@ class SiteTags(Table): ", ".join(self.columns) if site_tag_filter is not None: - if isinstance(site_tag_filter, (list, tuple, set, int, long)): + if isinstance(site_tag_filter, (list, tuple, set, int)): site_tag_filter = Filter(SiteTag.fields, {'site_tag_id': site_tag_filter}) elif isinstance(site_tag_filter, dict): site_tag_filter = Filter(SiteTag.fields, site_tag_filter) else: - raise PLCInvalidArgument, "Wrong site setting filter %r"%site_tag_filter + raise PLCInvalidArgument("Wrong site setting filter %r"%site_tag_filter) sql += " AND (%s) %s" % site_tag_filter.sql(api) diff --git a/PLC/Sites.py b/PLC/Sites.py index 20754092..213cd9ae 100644 --- a/PLC/Sites.py +++ b/PLC/Sites.py @@ -59,7 +59,7 @@ class Site(Row): def validate_name(self, name): if not len(name): - raise PLCInvalidArgument, "Name must be specified" + raise PLCInvalidArgument("Name must be specified") return name @@ -67,29 +67,29 @@ class Site(Row): def validate_login_base(self, login_base): if not len(login_base): - raise PLCInvalidArgument, "Login base must be specified" + raise PLCInvalidArgument("Login base must be specified") if not set(login_base).issubset(string.lowercase + string.digits + '.'): - raise PLCInvalidArgument, "Login base must consist only of lowercase ASCII letters or numbers or dots" + raise PLCInvalidArgument("Login base must consist only of lowercase ASCII letters or numbers or dots") conflicts = Sites(self.api, [login_base]) for site in conflicts: if 'site_id' not in self or self['site_id'] != site['site_id']: - raise PLCInvalidArgument, "login_base already in use" + raise PLCInvalidArgument("login_base already in use") return login_base def validate_latitude(self, latitude): - if not self.has_key('longitude') or \ + if 'longitude' not in self or \ self['longitude'] is None: - raise PLCInvalidArgument, "Longitude must also be specified" + raise PLCInvalidArgument("Longitude must also be specified") return latitude def validate_longitude(self, longitude): - if not self.has_key('latitude') or \ + if 'latitude' not in self or \ self['latitude'] is None: - raise PLCInvalidArgument, "Latitude must also be specified" + raise PLCInvalidArgument("Latitude must also be specified") return longitude @@ -130,7 +130,7 @@ class Site(Row): # Translate emails into person_ids if emails: persons = Persons(self.api, emails, ['person_id']).dict('person_id') - person_ids += persons.keys() + person_ids += list(persons.keys()) # Add new ids, remove stale ids if self['person_ids'] != person_ids: @@ -173,8 +173,8 @@ class Site(Row): from PLC.Methods.AddSiteAddress import AddSiteAddress from PLC.Methods.UpdateAddress import UpdateAddress - updated_addresses = filter(lambda address: 'address_id' in address, addresses) - added_addresses = filter(lambda address: 'address_id' not in address, addresses) + updated_addresses = [address for address in addresses if 'address_id' in address] + added_addresses = [address for address in addresses if 'address_id' not in address] for address in added_addresses: AddSiteAddress.__call__(AddSiteAddress(self.api), auth, self['site_id'], address) @@ -248,26 +248,26 @@ class Sites(Table): Site.primary_key) sql = "SELECT %s FROM %s WHERE deleted IS False" % \ - (", ".join(self.columns.keys()+self.tag_columns.keys()),view) + (", ".join(list(self.columns.keys())+list(self.tag_columns.keys())),view) if site_filter is not None: if isinstance(site_filter, (list, tuple, set)): # Separate the list into integers and strings - ints = filter(lambda x: isinstance(x, (int, long)), site_filter) - strs = filter(lambda x: isinstance(x, StringTypes), site_filter) + ints = [x for x in site_filter if isinstance(x, int)] + strs = [x for x in site_filter if isinstance(x, StringTypes)] site_filter = Filter(Site.fields, {'site_id': ints, 'login_base': strs}) sql += " AND (%s) %s" % site_filter.sql(api, "OR") elif isinstance(site_filter, dict): - allowed_fields=dict(Site.fields.items()+Site.tags.items()) + allowed_fields=dict(list(Site.fields.items())+list(Site.tags.items())) site_filter = Filter(allowed_fields, site_filter) sql += " AND (%s) %s" % site_filter.sql(api, "AND") elif isinstance (site_filter, StringTypes): site_filter = Filter(Site.fields, {'login_base':site_filter}) sql += " AND (%s) %s" % site_filter.sql(api, "AND") - elif isinstance (site_filter, (int, long)): + elif isinstance (site_filter, int): site_filter = Filter(Site.fields, {'site_id':site_filter}) sql += " AND (%s) %s" % site_filter.sql(api, "AND") else: - raise PLCInvalidArgument, "Wrong site filter %r"%site_filter + raise PLCInvalidArgument("Wrong site filter %r"%site_filter) self.selectall(sql) diff --git a/PLC/SliceInstantiations.py b/PLC/SliceInstantiations.py index c0658d4c..fd803a92 100644 --- a/PLC/SliceInstantiations.py +++ b/PLC/SliceInstantiations.py @@ -25,12 +25,12 @@ class SliceInstantiation(Row): def validate_instantiation(self, instantiation): # Make sure name is not blank if not len(instantiation): - raise PLCInvalidArgument, "Slice instantiation state name must be specified" + raise PLCInvalidArgument("Slice instantiation state name must be specified") # Make sure slice instantiation does not alredy exist conflicts = SliceInstantiations(self.api, [instantiation]) if conflicts: - raise PLCInvalidArgument, "Slice instantiation state name already in use" + raise PLCInvalidArgument("Slice instantiation state name already in use") return instantiation diff --git a/PLC/SliceTags.py b/PLC/SliceTags.py index e5070fd5..2ba7a018 100644 --- a/PLC/SliceTags.py +++ b/PLC/SliceTags.py @@ -45,12 +45,12 @@ class SliceTags(Table): ", ".join(self.columns) if slice_tag_filter is not None: - if isinstance(slice_tag_filter, (list, tuple, set, int, long)): + if isinstance(slice_tag_filter, (list, tuple, set, int)): slice_tag_filter = Filter(SliceTag.fields, {'slice_tag_id': slice_tag_filter}) elif isinstance(slice_tag_filter, dict): slice_tag_filter = Filter(SliceTag.fields, slice_tag_filter) else: - raise PLCInvalidArgument, "Wrong slice tag filter %r"%slice_tag_filter + raise PLCInvalidArgument("Wrong slice tag filter %r"%slice_tag_filter) sql += " AND (%s) %s" % slice_tag_filter.sql(api) self.selectall(sql) diff --git a/PLC/Slices.py b/PLC/Slices.py index e5a51ebe..606273f3 100644 --- a/PLC/Slices.py +++ b/PLC/Slices.py @@ -63,19 +63,19 @@ class Slice(Row): good_name = r'^[a-z0-9\.]+_[a-zA-Z0-9_\.]+$' if not name or \ not re.match(good_name, name): - raise PLCInvalidArgument, "Invalid slice name" + raise PLCInvalidArgument("Invalid slice name") conflicts = Slices(self.api, [name]) for slice in conflicts: if 'slice_id' not in self or self['slice_id'] != slice['slice_id']: - raise PLCInvalidArgument, "Slice name already in use, %s"%name + raise PLCInvalidArgument("Slice name already in use, %s"%name) return name def validate_instantiation(self, instantiation): instantiations = [row['instantiation'] for row in SliceInstantiations(self.api)] if instantiation not in instantiations: - raise PLCInvalidArgument, "No such instantiation state" + raise PLCInvalidArgument("No such instantiation state") return instantiation @@ -111,7 +111,7 @@ class Slice(Row): # Translate emails into person_ids if emails: persons = Persons(self.api, emails, ['person_id']).dict('person_id') - person_ids += persons.keys() + person_ids += list(persons.keys()) # Add new ids, remove stale ids if self['person_ids'] != person_ids: @@ -142,7 +142,7 @@ class Slice(Row): # Translate hostnames into node_ids if hostnames: nodes = Nodes(self.api, hostnames, ['node_id']).dict('node_id') - node_ids += nodes.keys() + node_ids += list(nodes.keys()) # Add new ids, remove stale ids if self['node_ids'] != node_ids: @@ -183,8 +183,8 @@ class Slice(Row): from PLC.Methods.AddSliceTag import AddSliceTag from PLC.Methods.UpdateSliceTag import UpdateSliceTag - added_attributes = filter(lambda x: 'slice_tag_id' not in x, attributes) - updated_attributes = filter(lambda x: 'slice_tag_id' in x, attributes) + added_attributes = [x for x in attributes if 'slice_tag_id' not in x] + updated_attributes = [x for x in attributes if 'slice_tag_id' in x] for added_attribute in added_attributes: if 'tag_type' in added_attribute: @@ -192,12 +192,12 @@ class Slice(Row): elif 'tag_type_id' in added_attribute: type = added_attribute['tag_type_id'] else: - raise PLCInvalidArgument, "Must specify tag_type or tag_type_id" + raise PLCInvalidArgument("Must specify tag_type or tag_type_id") if 'value' in added_attribute: value = added_attribute['value'] else: - raise PLCInvalidArgument, "Must specify a value" + raise PLCInvalidArgument("Must specify a value") if 'node_id' in added_attribute: node_id = added_attribute['node_id'] @@ -213,7 +213,7 @@ class Slice(Row): for updated_attribute in updated_attributes: attribute_id = updated_attribute.pop('slice_tag_id') if attribute_id not in self['slice_tag_ids']: - raise PLCInvalidArgument, "Attribute doesnt belong to this slice" + raise PLCInvalidArgument("Attribute doesnt belong to this slice") else: UpdateSliceTag.__call__(UpdateSliceTag(self.api), auth, attribute_id, updated_attribute) @@ -264,7 +264,7 @@ class Slices(Table): Slice.primary_key) sql = "SELECT %s FROM %s WHERE is_deleted IS False" % \ - (", ".join(self.columns.keys()+self.tag_columns.keys()),view) + (", ".join(list(self.columns.keys())+list(self.tag_columns.keys())),view) if expires is not None: if expires >= 0: @@ -276,21 +276,21 @@ class Slices(Table): if slice_filter is not None: if isinstance(slice_filter, (list, tuple, set)): # Separate the list into integers and strings - ints = filter(lambda x: isinstance(x, (int, long)), slice_filter) - strs = filter(lambda x: isinstance(x, StringTypes), slice_filter) + ints = [x for x in slice_filter if isinstance(x, int)] + strs = [x for x in slice_filter if isinstance(x, StringTypes)] slice_filter = Filter(Slice.fields, {'slice_id': ints, 'name': strs}) sql += " AND (%s) %s" % slice_filter.sql(api, "OR") elif isinstance(slice_filter, dict): - allowed_fields=dict(Slice.fields.items()+Slice.tags.items()) + allowed_fields=dict(list(Slice.fields.items())+list(Slice.tags.items())) slice_filter = Filter(allowed_fields, slice_filter) sql += " AND (%s) %s" % slice_filter.sql(api, "AND") elif isinstance (slice_filter, StringTypes): slice_filter = Filter(Slice.fields, {'name':slice_filter}) sql += " AND (%s) %s" % slice_filter.sql(api, "AND") - elif isinstance (slice_filter, (int, long)): + elif isinstance (slice_filter, int): slice_filter = Filter(Slice.fields, {'slice_id':slice_filter}) sql += " AND (%s) %s" % slice_filter.sql(api, "AND") else: - raise PLCInvalidArgument, "Wrong slice filter %r"%slice_filter + raise PLCInvalidArgument("Wrong slice filter %r"%slice_filter) self.selectall(sql) diff --git a/PLC/Table.py b/PLC/Table.py index 23659658..9d7d03ca 100644 --- a/PLC/Table.py +++ b/PLC/Table.py @@ -58,11 +58,11 @@ class Row(dict): # Warn about mandatory fields mandatory_fields = self.api.db.fields(self.table_name, notnull = True, hasdef = False) for field in mandatory_fields: - if not self.has_key(field) or self[field] is None: - raise PLCInvalidArgument, field + " must be specified and cannot be unset in class %s"%self.__class__.__name__ + if field not in self or self[field] is None: + raise PLCInvalidArgument(field + " must be specified and cannot be unset in class %s"%self.__class__.__name__) # Validate values before committing - for key, value in self.iteritems(): + for key, value in self.items(): if value is not None and hasattr(self, 'validate_' + key): validate = getattr(self, 'validate_' + key) self[key] = validate(value) @@ -74,12 +74,12 @@ class Row(dict): """ if isinstance(items, (list, tuple, set)): - ints = filter(lambda x: isinstance(x, (int, long)), items) - strs = filter(lambda x: isinstance(x, StringTypes), items) - dicts = filter(lambda x: isinstance(x, dict), items) + ints = [x for x in items if isinstance(x, int)] + strs = [x for x in items if isinstance(x, StringTypes)] + dicts = [x for x in items if isinstance(x, dict)] return (ints, strs, dicts) else: - raise PLCInvalidArgument, "Can only separate list types" + raise PLCInvalidArgument("Can only separate list types") def associate(self, *args): @@ -89,12 +89,12 @@ class Row(dict): """ if len(args) < 3: - raise PLCInvalidArgumentCount, "auth, field, value must be specified" + raise PLCInvalidArgumentCount("auth, field, value must be specified") elif hasattr(self, 'associate_' + args[1]): associate = getattr(self, 'associate_'+args[1]) associate(*args) else: - raise PLCInvalidArguemnt, "No such associate function associate_%s" % args[1] + raise PLCInvalidArguemnt("No such associate function associate_%s" % args[1]) def validate_timestamp (self, timestamp): return Timestamp.sql_validate(timestamp) @@ -126,7 +126,7 @@ class Row(dict): obj.primary_key: obj[obj.primary_key]} params = [] - for name, value in columns.iteritems(): + for name, value in columns.items(): params.append(self.api.db.param(name, value)) self.api.db.do("INSERT INTO %s (%s) VALUES(%s)" % \ @@ -197,7 +197,7 @@ class Row(dict): obj = self db_fields = self.api.db.fields(self.table_name) - return dict ( [ (key, value) for (key, value) in obj.items() + return dict ( [ (key, value) for (key, value) in list(obj.items()) if key in db_fields and Row.is_writable(key, value, self.fields) ] ) @@ -207,7 +207,7 @@ class Row(dict): """ if obj is None: obj=self - return dict ( [ (key,value) for (key,value) in obj.iteritems() + return dict ( [ (key,value) for (key,value) in obj.items() if key in self.tags and Row.is_writable(key,value,self.tags) ] ) # takes as input a list of columns, sort native fields from tags @@ -227,7 +227,7 @@ class Row(dict): @staticmethod def accepted_fields (update_columns, fields_dict, exclude=False): result={} - for (k,v) in fields_dict.iteritems(): + for (k,v) in fields_dict.items(): if (not exclude and k in update_columns) or (exclude and k not in update_columns): result[k]=v return result @@ -240,7 +240,7 @@ class Row(dict): # avoid the simple, but silent, version # return dict ([ (k,v) for (k,v) in user_dict.items() if k in accepted_fields ]) result={} - for (k,v) in user_dict.items(): + for (k,v) in list(user_dict.items()): if k in accepted_fields: result[k]=v else: raise PLCInvalidArgument ('Trying to set/change unaccepted key %s'%k) return result @@ -253,11 +253,11 @@ class Row(dict): result=[] for x in dicts: result.append({}) rejected={} - for (field,value) in fields.iteritems(): + for (field,value) in fields.items(): found=False for i in range(len(dicts)): candidate_dict=dicts[i] - if field in candidate_dict.keys(): + if field in list(candidate_dict.keys()): result[i][field]=value found=True break @@ -280,7 +280,7 @@ class Row(dict): """ if not cls.view_tags_name: - raise Exception, 'WARNING: class %s needs to set view_tags_name'%cls.__name__ + raise Exception('WARNING: class %s needs to set view_tags_name'%cls.__name__) table_name=cls.table_name primary_key=cls.primary_key @@ -298,7 +298,7 @@ class Row(dict): @classmethod def tagvalue_views_create (cls,api): if not cls.tags: return - for tagname in cls.tags.keys(): + for tagname in list(cls.tags.keys()): api.db.do(cls.tagvalue_view_create_sql (tagname)) api.db.commit() @@ -328,13 +328,13 @@ class Row(dict): db_fields = self.db_fields() # Parameterize for safety - keys = db_fields.keys() - values = [self.api.db.param(key, value) for (key, value) in db_fields.items()] + keys = list(db_fields.keys()) + values = [self.api.db.param(key, value) for (key, value) in list(db_fields.items())] # If the primary key (usually an auto-incrementing serial # identifier) has not been specified, or the primary key is the # only field in the table, or insert has been forced. - if not self.has_key(self.primary_key) or \ + if self.primary_key not in self or \ keys == [self.primary_key] or \ insert is True: @@ -344,8 +344,8 @@ class Row(dict): pk_id = self.api.db.next_id(self.table_name, self.primary_key) self[self.primary_key] = pk_id db_fields[self.primary_key] = pk_id - keys = db_fields.keys() - values = [self.api.db.param(key, value) for (key, value) in db_fields.items()] + keys = list(db_fields.keys()) + values = [self.api.db.param(key, value) for (key, value) in list(db_fields.items())] # Insert new row sql = "INSERT INTO %s (%s) VALUES (%s)" % \ (self.table_name, ", ".join(keys), ", ".join(values)) @@ -403,9 +403,9 @@ class Table(list): else: (columns,tag_columns,rejected) = classobj.parse_columns(columns) if not columns and not tag_columns: - raise PLCInvalidArgument, "No valid return fields specified for class %s"%classobj.__name__ + raise PLCInvalidArgument("No valid return fields specified for class %s"%classobj.__name__) if rejected: - raise PLCInvalidArgument, "unknown column(s) specified %r in %s"%(rejected,classobj.__name__) + raise PLCInvalidArgument("unknown column(s) specified %r in %s"%(rejected,classobj.__name__)) self.columns = columns self.tag_columns = tag_columns diff --git a/PLC/TagTypes.py b/PLC/TagTypes.py index f5524356..5fd924b2 100644 --- a/PLC/TagTypes.py +++ b/PLC/TagTypes.py @@ -31,13 +31,13 @@ class TagType (Row): def validate_name(self, name): if not len(name): - raise PLCInvalidArgument, "tag type name must be set" + raise PLCInvalidArgument("tag type name must be set") conflicts = TagTypes(self.api, [name]) for tag_type in conflicts: if 'tag_type_id' not in self or \ self['tag_type_id'] != tag_type['tag_type_id']: - raise PLCInvalidArgument, "tag type name already in use" + raise PLCInvalidArgument("tag type name already in use") return name @@ -60,20 +60,20 @@ class TagTypes(Table): if tag_type_filter is not None: if isinstance(tag_type_filter, (list, tuple, set)): # Separate the list into integers and strings - ints = filter(lambda x: isinstance(x, (int, long)), tag_type_filter) - strs = filter(lambda x: isinstance(x, StringTypes), tag_type_filter) + ints = [x for x in tag_type_filter if isinstance(x, int)] + strs = [x for x in tag_type_filter if isinstance(x, StringTypes)] tag_type_filter = Filter(TagType.fields, {'tag_type_id': ints, 'tagname': strs}) sql += " AND (%s) %s" % tag_type_filter.sql(api, "OR") elif isinstance(tag_type_filter, dict): tag_type_filter = Filter(TagType.fields, tag_type_filter) sql += " AND (%s) %s" % tag_type_filter.sql(api, "AND") - elif isinstance(tag_type_filter, (int, long)): + elif isinstance(tag_type_filter, int): tag_type_filter = Filter(TagType.fields, {'tag_type_id':tag_type_filter}) sql += " AND (%s) %s" % tag_type_filter.sql(api, "AND") elif isinstance(tag_type_filter, StringTypes): tag_type_filter = Filter(TagType.fields, {'tagname':tag_type_filter}) sql += " AND (%s) %s" % tag_type_filter.sql(api, "AND") else: - raise PLCInvalidArgument, "Wrong tag type filter %r"%tag_type_filter + raise PLCInvalidArgument("Wrong tag type filter %r"%tag_type_filter) self.selectall(sql) diff --git a/PLC/Timestamp.py b/PLC/Timestamp.py index 9f382ece..149c6e5d 100644 --- a/PLC/Timestamp.py +++ b/PLC/Timestamp.py @@ -62,7 +62,7 @@ class Timestamp: if not timezone: output_format = Timestamp.sql_format else: output_format = Timestamp.sql_format_utc - if Timestamp.debug: print 'sql_validate, in:',input, + if Timestamp.debug: print('sql_validate, in:',input, end=' ') if isinstance(input, StringTypes): sql='' # calendar.timegm() is the inverse of time.gmtime() @@ -75,20 +75,20 @@ class Timestamp: except ValueError: pass # could not parse it if not sql: - raise PLCInvalidArgument, "Cannot parse timestamp %r - not in any of %r formats"%(input,Timestamp.input_formats) - elif isinstance (input,(int,long,float)): + raise PLCInvalidArgument("Cannot parse timestamp %r - not in any of %r formats"%(input,Timestamp.input_formats)) + elif isinstance (input,(int,float)): try: - timestamp = long(input) + timestamp = int(input) sql = time.strftime(output_format, time.gmtime(timestamp)) - except Exception,e: - raise PLCInvalidArgument, "Timestamp %r not recognized -- %r"%(input,e) + except Exception as e: + raise PLCInvalidArgument("Timestamp %r not recognized -- %r"%(input,e)) else: - raise PLCInvalidArgument, "Timestamp %r - unsupported type %r"%(input,type(input)) + raise PLCInvalidArgument("Timestamp %r - unsupported type %r"%(input,type(input))) if check_future and input < time.time(): - raise PLCInvalidArgument, "'%s' not in the future" % sql + raise PLCInvalidArgument("'%s' not in the future" % sql) - if Timestamp.debug: print 'sql_validate, out:',sql + if Timestamp.debug: print('sql_validate, out:',sql) return sql @staticmethod @@ -106,23 +106,23 @@ class Timestamp: 00:00:00 GMT), a string (in one of the supported input formats above). """ - if Timestamp.debug: print 'cast_long, in:',input, + if Timestamp.debug: print('cast_long, in:',input, end=' ') if isinstance(input, StringTypes): timestamp=0 for time_format in Timestamp.input_formats: try: result=calendar.timegm(time.strptime(input, time_format)) - if Timestamp.debug: print 'out:',result + if Timestamp.debug: print('out:',result) return result # wrong format: ignore except ValueError: pass - raise PLCInvalidArgument, "Cannot parse timestamp %r - not in any of %r formats"%(input,Timestamp.input_formats) - elif isinstance (input,(int,long,float)): - result=long(input) - if Timestamp.debug: print 'out:',result + raise PLCInvalidArgument("Cannot parse timestamp %r - not in any of %r formats"%(input,Timestamp.input_formats)) + elif isinstance (input,(int,float)): + result=int(input) + if Timestamp.debug: print('out:',result) return result else: - raise PLCInvalidArgument, "Timestamp %r - unsupported type %r"%(input,type(input)) + raise PLCInvalidArgument("Timestamp %r - unsupported type %r"%(input,type(input))) # utility for displaying durations @@ -151,6 +151,6 @@ class Duration: def validate (duration): # support seconds only for now, works for int/long/str try: - return long (duration) + return int (duration) except: - raise PLCInvalidArgument, "Could not parse duration %r"%duration + raise PLCInvalidArgument("Could not parse duration %r"%duration) diff --git a/PLC/sendmail.py b/PLC/sendmail.py index a5f0c5e8..accb0bb1 100644 --- a/PLC/sendmail.py +++ b/PLC/sendmail.py @@ -96,4 +96,4 @@ def sendmail(api, To, Subject, Body, From = None, Cc = None, Bcc = None): s.close() if rejected: - raise PLCAPIError, "Error sending message to " + ", ".join(rejected.keys()) + raise PLCAPIError("Error sending message to " + ", ".join(list(rejected.keys()))) diff --git a/Server.py b/Server.py index 4a0dc297..7b07264f 100755 --- a/Server.py +++ b/Server.py @@ -10,14 +10,14 @@ import os import sys import getopt import traceback -import BaseHTTPServer +import http.server # Append PLC to the system path sys.path.append(os.path.dirname(os.path.realpath(sys.argv[0]))) from PLC.API import PLCAPI -class PLCAPIRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): +class PLCAPIRequestHandler(http.server.BaseHTTPRequestHandler): """ Simple standalone HTTP request handler for testing PLCAPI. """ @@ -40,7 +40,7 @@ class PLCAPIRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): self.wfile.flush() self.connection.shutdown(1) - except Exception, e: + except Exception as e: # Log error sys.stderr.write(traceback.format_exc()) sys.stderr.flush() @@ -58,7 +58,7 @@ class PLCAPIRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): """) -class PLCAPIServer(BaseHTTPServer.HTTPServer): +class PLCAPIServer(http.server.HTTPServer): """ Simple standalone HTTP server for testing PLCAPI. """ @@ -66,7 +66,7 @@ class PLCAPIServer(BaseHTTPServer.HTTPServer): def __init__(self, addr, config): self.api = PLCAPI(config) self.allow_reuse_address = 1 - BaseHTTPServer.HTTPServer.__init__(self, addr, PLCAPIRequestHandler) + http.server.HTTPServer.__init__(self, addr, PLCAPIRequestHandler) # Defaults addr = "0.0.0.0" @@ -74,18 +74,18 @@ port = 8000 config = "/etc/planetlab/plc_config" def usage(): - print "Usage: %s [OPTION]..." % sys.argv[0] - print "Options:" - print " -p PORT, --port=PORT TCP port number to listen on (default: %d)" % port - print " -f FILE, --config=FILE PLC configuration file (default: %s)" % config - print " -h, --help This message" + print("Usage: %s [OPTION]..." % sys.argv[0]) + print("Options:") + print(" -p PORT, --port=PORT TCP port number to listen on (default: %d)" % port) + print(" -f FILE, --config=FILE PLC configuration file (default: %s)" % config) + print(" -h, --help This message") sys.exit(1) # Get options try: (opts, argv) = getopt.getopt(sys.argv[1:], "p:f:h", ["port=", "config=", "help"]) -except getopt.GetoptError, err: - print "Error: " + err.msg +except getopt.GetoptError as err: + print("Error: " + err.msg) usage() for (opt, optval) in opts: diff --git a/apache/ModPython.py b/apache/ModPython.py index c0918946..af9130f7 100644 --- a/apache/ModPython.py +++ b/apache/ModPython.py @@ -10,7 +10,7 @@ import sys import time import traceback -import xmlrpclib +import xmlrpc.client from mod_python import apache from PLC.Logger import logger diff --git a/apache/ModPythonJson.py b/apache/ModPythonJson.py index 78cb3638..3534c502 100644 --- a/apache/ModPythonJson.py +++ b/apache/ModPythonJson.py @@ -9,7 +9,7 @@ import sys import traceback -import xmlrpclib +import xmlrpc.client from mod_python import apache from PLC.Logger import logger @@ -55,6 +55,6 @@ def handler(req): return apache.OK - except Exception, err: + except Exception as err: logger.exception("INTERNAL ERROR !!") return apache.HTTP_INTERNAL_SERVER_ERROR diff --git a/aspects/ratelimitaspects.py b/aspects/ratelimitaspects.py index 836b2bab..d2aa40d0 100644 --- a/aspects/ratelimitaspects.py +++ b/aspects/ratelimitaspects.py @@ -145,13 +145,12 @@ Subject: %(subject)s if (api_method == "session" and api_method_caller.__contains__("@")) or (api_method == "password" or api_method == "capability"): self.mail(api_method_caller) - raise PLCPermissionDenied, "Maximum allowed number of API calls exceeded" + raise PLCPermissionDenied("Maximum allowed number of API calls exceeded") def after(self, wobj, data, *args, **kwargs): return -class RateLimitAspect_class(BaseRateLimit): - __metaclass__ = MetaAspect +class RateLimitAspect_class(BaseRateLimit, metaclass=MetaAspect): name = "ratelimitaspect_class" def __init__(self): diff --git a/cache_utils/tests.py b/cache_utils/tests.py index b55857e0..56333d81 100644 --- a/cache_utils/tests.py +++ b/cache_utils/tests.py @@ -51,7 +51,7 @@ class FuncInfoTest(TestCase): class SanitizeTest(TestCase): def test_sanitize_keys(self): - key = u"12345678901234567890123456789012345678901234567890" + key = "12345678901234567890123456789012345678901234567890" self.assertTrue(len(key) >= 40) key = sanitize_memcached_key(key, 40) self.assertTrue(len(key) <= 40) @@ -132,19 +132,19 @@ class DecoratorTest(ClearMemcachedTest): @cached(60, group='test-group') def my_func(params=""): self._x = self._x + 1 - return u"%d%s" % (self._x, params) + return "%d%s" % (self._x, params) self.assertEqual(my_func(), "1") self.assertEqual(my_func(), "1") - self.assertEqual(my_func("x"), u"2x") - self.assertEqual(my_func("x"), u"2x") + self.assertEqual(my_func("x"), "2x") + self.assertEqual(my_func("x"), "2x") - self.assertEqual(my_func(u"Василий"), u"3Василий") - self.assertEqual(my_func(u"Василий"), u"3Василий") + self.assertEqual(my_func("Василий"), "3Василий") + self.assertEqual(my_func("Василий"), "3Василий") - self.assertEqual(my_func(u"й"*240), u"4"+u"й"*240) - self.assertEqual(my_func(u"й"*240), u"4"+u"й"*240) + self.assertEqual(my_func("й"*240), "4"+"й"*240) + self.assertEqual(my_func("й"*240), "4"+"й"*240) - self.assertEqual(my_func(u"Ы"*500), u"5"+u"Ы"*500) - self.assertEqual(my_func(u"Ы"*500), u"5"+u"Ы"*500) + self.assertEqual(my_func("Ы"*500), "5"+"Ы"*500) + self.assertEqual(my_func("Ы"*500), "5"+"Ы"*500) diff --git a/cache_utils/utils.py b/cache_utils/utils.py index ed7474df..c6ecca0f 100644 --- a/cache_utils/utils.py +++ b/cache_utils/utils.py @@ -17,15 +17,15 @@ def sanitize_memcached_key(key, max_length=250): def _args_to_unicode(args, kwargs): key = "" if args: - key += unicode(args) + key += str(args) if kwargs: - key += unicode(kwargs) + key += str(kwargs) return key def _func_type(func): """ returns if callable is a function, method or a classmethod """ - argnames = func.func_code.co_varnames[:func.func_code.co_argcount] + argnames = func.__code__.co_varnames[:func.__code__.co_argcount] if len(argnames) > 0: if argnames[0] == 'self': return 'method' diff --git a/doc/DocBook.py b/doc/DocBook.py index 90b384d7..edc42ca5 100755 --- a/doc/DocBook.py +++ b/doc/DocBook.py @@ -18,7 +18,7 @@ from PLC.Parameter import Parameter, Mixed, xmlrpc_type, python_type class TrimText(Text): """text""" def __init__(self, text = None): - self.data = unicode(text) + self.data = str(text) def writexml(self, writer, indent="", addindent="", newl=""): Text.writexml(self, writer, "", "", "") @@ -91,7 +91,7 @@ class paramElement(Element): if isinstance(param, dict): itemizedlist = Element('itemizedlist') self.appendChild(itemizedlist) - for name, subparam in param.iteritems(): + for name, subparam in param.items(): itemizedlist.appendChild(paramElement(name, subparam)) elif isinstance(param, (list, tuple, set)) and len(param): @@ -148,4 +148,4 @@ class DocBook: returns.appendChild(paramElement(None, func.returns)) section.appendChild(returns) - print section.toprettyxml(encoding = "UTF-8") + print(section.toprettyxml(encoding = "UTF-8")) diff --git a/migrations/extract-views.py b/migrations/extract-views.py index 4fd5090e..02a75242 100755 --- a/migrations/extract-views.py +++ b/migrations/extract-views.py @@ -46,7 +46,7 @@ class Schema: if __name__ == '__main__': if len(sys.argv) not in [2,3]: - print 'Usage:',sys.argv[0],'input [output]' + print('Usage:',sys.argv[0],'input [output]') sys.exit(1) input=sys.argv[1] try: diff --git a/tools/dzombie.py b/tools/dzombie.py index 2095c964..d54a5557 100755 --- a/tools/dzombie.py +++ b/tools/dzombie.py @@ -10,16 +10,16 @@ from pprint import pprint schema_file = None config_file = "/etc/planetlab/plc_config" config = {} -execfile(config_file, config) +exec(compile(open(config_file).read(), config_file, 'exec'), config) def usage(): - print "Usage: %s SCHEMA_FILE " % sys.argv[0] + print("Usage: %s SCHEMA_FILE " % sys.argv[0]) sys.exit(1) try: schema_file = sys.argv[1] except IndexError: - print "Error: too few arguments" + print("Error: too few arguments") usage() # all foreing keys exist as primary kyes in another table @@ -97,7 +97,7 @@ try: result = desc.readlines() if primary_key_parts[0] in ['slices']: sql = sql + " where name not like '%_deleted'" - elif filter(lambda line: line.find("deleted") > -1, result): + elif [line for line in result if line.find("deleted") > -1]: sql = sql + " where deleted = false" cursor.execute(sql) @@ -107,16 +107,16 @@ try: # also, ignore null foreign keys, not considered zombied zombie_keys_func = lambda key: key not in primary_key_rows and not key == [None] zombie_keys_list = [zombie_key[0] for zombie_key in filter(zombie_keys_func, foreign_rows)] - print zombie_keys_list + print(zombie_keys_list) # delete these zombie records if zombie_keys_list: - print " -> Deleting %d zombie record(s) from %s after checking %s" % \ - (len(zombie_keys_list), foreign_key_parts[0], primary_key_parts[0]) + print(" -> Deleting %d zombie record(s) from %s after checking %s" % \ + (len(zombie_keys_list), foreign_key_parts[0], primary_key_parts[0])) sql_delete = 'DELETE FROM %s WHERE %s IN %s' % \ (foreign_key_parts[0], foreign_key_parts[1], tuple(zombie_keys_list)) cursor.execute(sql_delete) db.commit() #zombie_keys[foreign_key] = zombie_keys_list - print "done" + print("done") except pgdb.DatabaseError: raise diff --git a/tools/slice_attributes.py b/tools/slice_attributes.py index 471bc53d..1efab362 100755 --- a/tools/slice_attributes.py +++ b/tools/slice_attributes.py @@ -16,7 +16,7 @@ rename = {'nm_net_min_rate': 'net_min_rate', 'nm_net_max_rate': 'net_max_rate', 'nm_net_exempt_min_rate': 'net_i2_min_rate', 'nm_net_exempt_max_rate': 'net_i2_max_rate'} -for slice_attribute in GetSliceTags({'name': rename.keys()}): +for slice_attribute in GetSliceTags({'name': list(rename.keys())}): id = slice_attribute['slice_attribute_id'] name = slice_attribute['name'] slice_id = slice_attribute['slice_id'] @@ -38,7 +38,7 @@ rename = {'nm_net_avg_rate': {'max': 'net_max_kbyte', 'thresh': 'net_thresh_kbyte'}, 'nm_net_exempt_avg_rate': {'max': 'net_i2_max_kbyte', 'thresh': 'net_i2_thresh_kbyte'}} -for slice_attribute in GetSliceTags({'name': rename.keys()}): +for slice_attribute in GetSliceTags({'name': list(rename.keys())}): id = slice_attribute['slice_attribute_id'] name = slice_attribute['name'] slice_id = slice_attribute['slice_id'] @@ -81,7 +81,7 @@ rename = {'nm_cpu_share': 'cpu_share', 'nm_net_max_thresh_byte': 'net_thresh_kbyte', 'nm_net_max_exempt_byte': 'net_i2_max_kbyte', 'nm_net_max_thresh_exempt_byte': 'net_i2_thresh_kbyte'} -for slice_attribute in GetSliceTags({'name': rename.keys()}): +for slice_attribute in GetSliceTags({'name': list(rename.keys())}): id = slice_attribute['slice_attribute_id'] name = slice_attribute['name'] slice_id = slice_attribute['slice_id'] @@ -208,8 +208,8 @@ proper_ops = [ for slice, op in proper_ops: try: AddSliceTag(slice, 'proper_op', op) - except Exception, err: - print "Warning: %s:" % slice, err + except Exception as err: + print("Warning: %s:" % slice, err) initscripts = dict([(initscript['initscript_id'], initscript) for initscript in [{'initscript_id': 8, 'script': 'IyEgL2Jpbi9zaA0KDQojIDxQcm9ncmFtIE5hbWU+DQojICAgIGJpbmRzY3JpcHQNCiMNCiMgPEF1dGhvcj4NCiMgICAgSmVmZnJ5IEpvaG5zdG9uIGFuZCBKZXJlbXkgUGxpY2h0YQ0KIw0KIyA8UHVycG9zZT4NCiMgICAgRG93bmxvYWRzIGFuZCBpbnN0YWxscyBzdG9yayBvbiBhIG5vZGUuDQoNCiMgc2F2ZSBvcmlnaW5hbCB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WUgJ3MvXnVzZXJuYW1lLiovdXNlcm5hbWUgPSBoZWxsby8nIC91c3IvbG9jYWwvc3RvcmsvZXRjL3N0b3JrLmNvbmYNCg0KIyBJbnN0YWxsIFJQTQ0Kc3RvcmsgdXBncmFkZSBoZWxsbw0KDQojIGVuZA0KZXhpdCAwDQo=', 'name': 'princeton_hello_stork', 'encoding': 'base64'}, {'initscript_id': 10, 'script': 'IyEvYmluL2Jhc2gNCg0KIyBJbml0IHNjcmlwdCBmb3IgdGhlIFBsYW5ldExhYiAiSGVsbG8gV29ybGQiIGRlbW8gdXNpbmcgR29vZ2xlIEVhcnRoLg0KIyBJbnN0YWxscyBhIGNyb250YWIgZW50cnkgb24gdGhlIG5vZGUgdGhhdCBwaG9uZXMgaG9tZSB0byB0aGUgc2VydmVyDQojIGV2ZXJ5IHRocmVlIG1pbnV0ZXMuDQoNClNFUlZFUj0xMjguMTEyLjEzOS43Mzo4MDQyCQkjIHBsYW5ldGxhYi0zLmNzLnByaW5jZXRvbi5lZHUNCg0KL3Vzci9iaW4vY3VybCAtcyBodHRwOi8vJFNFUlZFUi8NCmVjaG8gIiovNSAqICogKiAqIC91c3IvYmluL2N1cmwgLXMgaHR0cDovLyRTRVJWRVIvIiB8IGNyb250YWIgLQ0KL3NiaW4vY2hrY29uZmlnIGNyb25kIG9uDQo=', 'name': 'princeton_hello', 'encoding': 'base64'}]]) @@ -223,7 +223,7 @@ for slice_attribute in GetSliceTags({'name': 'plc_initscript'}): DeleteSliceTag(id) if initscript_id not in initscripts: - print "Warning: Missing initscript %d" % initscript_id + print("Warning: Missing initscript %d" % initscript_id) continue initscript = base64.b64decode(initscripts[initscript_id]['script']) @@ -275,6 +275,6 @@ conf_file_id = AddConfFile({ AddConfFileToNodeGroup(conf_file_id, 'Rollout') # Add OneLab as a peer -onelab = {'peername': u'OneLab', 'peer_url': u'https://onelab-plc.inria.fr/PLCAPI/', 'key': u'-----BEGIN PGP PUBLIC KEY BLOCK-----\nVersion: GnuPG v1.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n2AzDnde\nITF0aYd02RAKsU4sKePEtEJPbmVMYWIgQ2VudHJhbCAoaHR0cDovL29uZWxhYi1w\nbGMuaW5yaWEuZnIvKSA8c3VwcG9ydEBvbmUtbGFiLm9yZz6IYAQTEQIAIAUCRbi2\npgIbIwYLCQgHAwIEFQIIAwQWAgMBAh4BAheAAAoJEG67sTS/MV31W4AAn0rW5yjR\n2a8jPP/V44gw1JhqnE8jAKCMAEh0nPjvle5oLEGectC3Es9Pm7kBDQRFtJCUEAQA\nhp38fNVy/aJiPg2lUKKnA6KjrRm3LxD66N8MSWfxGCIYzQRJHhmZWnS+m1DDOjdu\nFG9FM6QrsCRRcEQuvhKI2ORFfK75D24lj4QaXzw7vfBbAibTaDsYa0b5LxfR5pGj\nYPCQ5LrRex+Ws3DrB3acJE5/XnYJZ+rUO1ZJlm00FTMAAwUD/Ai4ZUunVB8F0VqS\nhJgDYQF08/OlAnDAcbL//P5dtXdztUNSgXZM4wW/XFnDvAsBuRnbfkT/3BeptM9L\neEbdrMi4eThLstSl13ITOsZbSL3i/2OO9sPAxupWzRWOXcQILpqR2YMRK1EapO+M\nNhjrgxU9JpMXz24FESocczSyywDXiEkEGBECAAkFAkW0kJQCGwwACgkQbruxNL8x\nXfXGxQCfZqzSqinohParWaHv+4XNoIz2B7IAn2Ge0O5wjYZeV/joulkTXfPKm7Iu\n=SsZg\n-----END PGP PUBLIC KEY BLOCK-----\n', 'cacert': u'Certificate:\r\n Data:\r\n Version: 3 (0x2)\r\n Serial Number: 67109883 (0x40003fb)\r\n Signature Algorithm: sha1WithRSAEncryption\r\n Issuer: C=US, O=GTE Corporation, OU=GTE CyberTrust Solutions, Inc., CN=G\r\n Validity\r\n Not Before: Mar 14 20:30:00 2006 GMT\r\n Not After : Mar 14 23:59:00 2013 GMT\r\n Subject: C=BE, O=Cybertrust, OU=Educational CA, CN=Cybertrust Educationa\r\n Subject Public Key Info:\r\n Public Key Algorithm: rsaEncryption\r\n RSA Public Key: (2048 bit)\r\n Modulus (2048 bit):\r\n 00:95:22:a1:10:1d:4a:46:60:6e:05:91:9b:df:83:\r\n c2:ed:12:b2:5a:7c:f8:ab:e1:f8:50:5c:28:2c:7e:\r\n 7e:00:38:93:b0:8b:4a:f1:c2:4c:3c:10:2c:3c:ef:\r\n b0:ec:a1:69:2f:b9:fc:cc:08:14:6b:8d:4f:18:f3:\r\n 83:d2:fa:a9:37:08:20:aa:5c:aa:80:60:a2:d5:a5:\r\n 22:00:cf:5a:e5:b4:97:df:ba:1e:be:5c:8e:17:19:\r\n 66:fd:af:9f:7c:7b:89:b2:0e:24:d8:c7:ab:63:c4:\r\n 95:32:8d:48:e6:63:59:7d:04:b8:33:a8:bd:d7:5d:\r\n 64:bc:63:b5:f7:4d:28:fd:f9:06:72:31:5c:ba:45:\r\n 94:65:a3:d2:b4:58:ec:3b:61:58:44:a3:2f:62:b3:\r\n 9b:80:b4:82:fd:d5:c7:cc:51:25:e5:95:3f:47:2f:\r\n 30:7b:ac:c8:78:6e:e2:e1:6d:27:eb:3d:cc:01:82:\r\n e8:35:77:8d:ab:58:bb:55:d1:d5:a4:81:56:8d:1c:\r\n d0:14:b1:b0:06:de:a0:91:22:f3:f0:a8:34:17:47:\r\n c6:e0:3e:f6:0c:5a:ac:7e:50:4b:cd:e1:69:6e:06:\r\n fc:06:7e:6a:4d:b4:95:99:a0:59:5c:35:66:ec:d9:\r\n 49:d4:17:e0:60:b0:5d:a5:d7:1a:e2:2a:6e:66:f2:\r\n af:1d\r\n Exponent: 65537 (0x10001)\r\n X509v3 extensions:\r\n X509v3 CRL Distribution Points: \r\n URI:http://www.public-trust.com/cgi-bin/CRL/2018/cdp.crl\r\n\r\n X509v3 Subject Key Identifier: \r\n 65:65:A3:3D:D7:3B:11:A3:0A:07:25:37:C9:42:4A:5B:76:77:50:E1\r\n X509v3 Certificate Policies: \r\n Policy: 1.3.6.1.4.1.6334.1.0\r\n CPS: http://www.public-trust.com/CPS/OmniRoot.html\r\n\r\n X509v3 Authority Key Identifier: \r\n DirName:/C=US/O=GTE Corporation/OU=GTE CyberTrust Solutions, Inc\r\n serial:01:A5\r\n\r\n X509v3 Key Usage: critical\r\n Certificate Sign, CRL Sign\r\n X509v3 Basic Constraints: critical\r\n CA:TRUE, pathlen:0\r\n Signature Algorithm: sha1WithRSAEncryption\r\n 43:b3:45:83:54:71:c4:1f:dc:b2:3c:6b:4e:bf:26:f2:4e:f2:\r\n ad:9a:5b:fa:86:37:88:e8:14:6c:41:18:42:5f:ef:65:3e:eb:\r\n 03:77:a0:b7:9e:75:7a:51:7c:bb:15:5b:b8:af:91:a0:34:92:\r\n 53:ed:7f:2a:49:84:ac:b9:80:4b:b5:c7:b2:23:22:fb:eb:d8:\r\n fb:6e:c9:3c:f3:d2:d1:bb:be:c9:1c:ff:6d:01:db:69:80:0e:\r\n 99:a5:ea:9e:7b:97:98:8f:b7:cf:22:9c:b3:b8:5d:e5:a9:33:\r\n 17:74:c6:97:37:0f:b4:e9:26:82:5f:61:0b:3f:1e:3d:64:e9:\r\n 2b:9b\r\n-----BEGIN CERTIFICATE-----\r\nMIIEQjCCA6ugAwIBAgIEBAAD+zANBgkqhkiG9w0BAQUFADB1MQswCQYDVQQGEwJV\r\nUzEYMBYGA1UEChMPR1RFIENvcnBvcmF0aW9uMScwJQYDVQQLEx5HVEUgQ3liZXJU\r\ncnVzdCBTb2x1dGlvbnMsIEluYy4xIzAhBgNVBAMTGkdURSBDeWJlclRydXN0IEds\r\nb2JhbCBSb290MB4XDTA2MDMxNDIwMzAwMFoXDTEzMDMxNDIzNTkwMFowXzELMAkG\r\nA1UEBhMCQkUxEzARBgNVBAoTCkN5YmVydHJ1c3QxFzAVBgNVBAsTDkVkdWNhdGlv\r\nbmFsIENBMSIwIAYDVQQDExlDeWJlcnRydXN0IEVkdWNhdGlvbmFsIENBMIIBIjAN\r\nBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlSKhEB1KRmBuBZGb34PC7RKyWnz4\r\nq+H4UFwoLH5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WTpK5s=\r\n-----END CERTIFICATE-----\r\nCertificate:\r\n Data:\r\n Version: 1 (0x0)\r\n Serial Number: 421 (0x1a5)\r\n Signature Algorithm: md5WithRSAEncryption\r\n Issuer: C=US, O=GTE Corporation, OU=GTE CyberTrust Solutions, Inc., CN=GTE CyberTrust Global Root\r\n Validity\r\n Not Before: Aug 13 00:29:00 1998 GMT\r\n Not After : Aug 13 23:59:00 2018 GMT\r\n Subject: C=US, O=GTE Corporation, OU=GTE CyberTrust Solutions, Inc., CN=GTE CyberTrust Global Root\r\n Subject Public Key Info:\r\n Public Key Algorithm: rsaEncryption\r\n RSA Public Key: (1024 bit)\r\n Modulus (1024 bit):\r\n 00:95:0f:a0:b6:f0:50:9c:e8:7a:c7:88:cd:dd:17:\r\n 0e:2e:b0:94:d0:1b:3d:0e:f6:94:c0:8a:94:c7:06:\r\n c8:90:97:c8:b8:64:1a:7a:7e:6c:3c:53:e1:37:28:\r\n 73:60:7f:b2:97:53:07:9f:53:f9:6d:58:94:d2:af:\r\n 8d:6d:88:67:80:e6:ed:b2:95:cf:72:31:ca:a5:1c:\r\n 72:ba:5c:02:e7:64:42:e7:f9:a9:2c:d6:3a:0d:ac:\r\n 8d:42:aa:24:01:39:e6:9c:3f:01:85:57:0d:58:87:\r\n 45:f8:d3:85:aa:93:69:26:85:70:48:80:3f:12:15:\r\n c7:79:b4:1f:05:2f:3b:62:99\r\n Exponent: 65537 (0x10001)\r\n Signature Algorithm: md5WithRSAEncryption\r\n 6d:eb:1b:09:e9:5e:d9:51:db:67:22:61:a4:2a:3c:48:77:e3:\r\n a0:7c:a6:de:73:a2:14:03:85:3d:fb:ab:0e:30:c5:83:16:33:\r\n 81:13:08:9e:7b:34:4e:df:40:c8:74:d7:b9:7d:dc:f4:76:55:\r\n 7d:9b:63:54:18:e9:f0:ea:f3:5c:b1:d9:8b:42:1e:b9:c0:95:\r\n 4e:ba:fa:d5:e2:7c:f5:68:61:bf:8e:ec:05:97:5f:5b:b0:d7:\r\n a3:85:34:c4:24:a7:0d:0f:95:93:ef:cb:94:d8:9e:1f:9d:5c:\r\n 85:6d:c7:aa:ae:4f:1f:22:b5:cd:95:ad:ba:a7:cc:f9:ab:0b:\r\n 7a:7f\r\n-----BEGIN CERTIFICATE-----\r\nMIICWjCCAcMCAgGlMA0GCSqGSIb3DQEBBAUAMHUxCzAJBgNVBAYTAlVTMRgwFgYD\r\nVQQKEw9HVEUgQ29ycG9yYXRpb24xJzAlBgNVBAsTHkdURSBDeWJlclRydXN0IFNv\r\nbHV0aW9ucywgSW5jLjEjMCEGA1UEAxMaR1RFIEN5YmVyVHJ1c3QgR2xvYmFsIFJv\r\nb3QwHhcNOTgwODEzMDAyOTAwWhcNMTgwODEzMjM1OTAwWjB1MQswCQYDVQQGEwJV\r\nUzEYMBYGA1UEChMPR1RFIENvcnBvcmF0aW9uMScwJQYDVQQLEx5HVEUgQ3liZXJU\r\ncnVzdCBTb2x1dGlvbnMsIEluYy4xIzAhBgNVBAMTGkdURSBDeWJlclRydXN0IEds\r\nb2JhbCBSb290MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCVD6C28FCc6HrH\r\niM3dFw4usJTQGz0O9pTAipTHBsiQl8i4ZBp6fmw8U+E3KHNgf7KXUwefU/ltWJTS\r\nr41tiGeA5u2ylc9yMcqlHHK6XALnZELn+aks1joNrI1CqiQBOeacPwGFVw1Yh0X4\r\n04Wqk2kmhXBIgD8SFcd5tB8FLztimQIDAQABMA0GCSqGSIb3DQEBBAUAA4GBAG3r\r\nGwnpXtlR22ciYaQqPEh346B8pt5zohQDhT37qw4wxYMWM4ETCJ57NE7fQMh017l9\r\n3PR2VX2bY1QY6fDq81yx2YtCHrnAlU66+tXifPVoYb+O7AWXX1uw16OFNMQkpw0P\r\nlZPvy5TYnh+dXIVtx6quTx8itc2VrbqnzPmrC3p/\r\n-----END CERTIFICATE-----\r\n'} +onelab = {'peername': 'OneLab', 'peer_url': 'https://onelab-plc.inria.fr/PLCAPI/', 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kQbruxNL8xXfU5UQCeKqXWeNzTqdMqj/qHPkp1JCb+isEAn2AzDnde\nITF0aYd02RAKsU4sKePEtEJPbmVMYWIgQ2VudHJhbCAoaHR0cDovL29uZWxhYi1w\nbGMuaW5yaWEuZnIvKSA8c3VwcG9ydEBvbmUtbGFiLm9yZz6IYAQTEQIAIAUCRbi2\npgIbIwYLCQgHAwIEFQIIAwQWAgMBAh4BAheAAAoJEG67sTS/MV31W4AAn0rW5yjR\n2a8jPP/V44gw1JhqnE8jAKCMAEh0nPjvle5oLEGectC3Es9Pm7kBDQRFtJCUEAQA\nhp38fNVy/aJiPg2lUKKnA6KjrRm3LxD66N8MSWfxGCIYzQRJHhmZWnS+m1DDOjdu\nFG9FM6QrsCRRcEQuvhKI2ORFfK75D24lj4QaXzw7vfBbAibTaDsYa0b5LxfR5pGj\nYPCQ5LrRex+Ws3DrB3acJE5/XnYJZ+rUO1ZJlm00FTMAAwUD/Ai4ZUunVB8F0VqS\nhJgDYQF08/OlAnDAcbL//P5dtXdztUNSgXZM4wW/XFnDvAsBuRnbfkT/3BeptM9L\neEbdrMi4eThLstSl13ITOsZbSL3i/2OO9sPAxupWzRWOXcQILpqR2YMRK1EapO+M\nNhjrgxU9JpMXz24FESocczSyywDXiEkEGBECAAkFAkW0kJQCGwwACgkQbruxNL8x\nXfXGxQCfZqzSqinohParWaHv+4XNoIz2B7IAn2Ge0O5wjYZeV/joulkTXfPKm7Iu\n=SsZg\n-----END PGP PUBLIC KEY BLOCK-----\n', 'cacert': 'Certificate:\r\n Data:\r\n Version: 3 (0x2)\r\n Serial Number: 67109883 (0x40003fb)\r\n Signature Algorithm: sha1WithRSAEncryption\r\n Issuer: C=US, O=GTE Corporation, OU=GTE CyberTrust Solutions, Inc., CN=G\r\n Validity\r\n Not Before: Mar 14 20:30:00 2006 GMT\r\n Not After : Mar 14 23:59:00 2013 GMT\r\n Subject: C=BE, O=Cybertrust, OU=Educational CA, CN=Cybertrust Educationa\r\n Subject Public Key Info:\r\n Public Key Algorithm: rsaEncryption\r\n RSA Public Key: (2048 bit)\r\n Modulus (2048 bit):\r\n 00:95:22:a1:10:1d:4a:46:60:6e:05:91:9b:df:83:\r\n c2:ed:12:b2:5a:7c:f8:ab:e1:f8:50:5c:28:2c:7e:\r\n 7e:00:38:93:b0:8b:4a:f1:c2:4c:3c:10:2c:3c:ef:\r\n b0:ec:a1:69:2f:b9:fc:cc:08:14:6b:8d:4f:18:f3:\r\n 83:d2:fa:a9:37:08:20:aa:5c:aa:80:60:a2:d5:a5:\r\n 22:00:cf:5a:e5:b4:97:df:ba:1e:be:5c:8e:17:19:\r\n 66:fd:af:9f:7c:7b:89:b2:0e:24:d8:c7:ab:63:c4:\r\n 95:32:8d:48:e6:63:59:7d:04:b8:33:a8:bd:d7:5d:\r\n 64:bc:63:b5:f7:4d:28:fd:f9:06:72:31:5c:ba:45:\r\n 94:65:a3:d2:b4:58:ec:3b:61:58:44:a3:2f:62:b3:\r\n 9b:80:b4:82:fd:d5:c7:cc:51:25:e5:95:3f:47:2f:\r\n 30:7b:ac:c8:78:6e:e2:e1:6d:27:eb:3d:cc:01:82:\r\n e8:35:77:8d:ab:58:bb:55:d1:d5:a4:81:56:8d:1c:\r\n d0:14:b1:b0:06:de:a0:91:22:f3:f0:a8:34:17:47:\r\n c6:e0:3e:f6:0c:5a:ac:7e:50:4b:cd:e1:69:6e:06:\r\n fc:06:7e:6a:4d:b4:95:99:a0:59:5c:35:66:ec:d9:\r\n 49:d4:17:e0:60:b0:5d:a5:d7:1a:e2:2a:6e:66:f2:\r\n af:1d\r\n Exponent: 65537 (0x10001)\r\n X509v3 extensions:\r\n X509v3 CRL Distribution Points: \r\n URI:http://www.public-trust.com/cgi-bin/CRL/2018/cdp.crl\r\n\r\n X509v3 Subject Key Identifier: \r\n 65:65:A3:3D:D7:3B:11:A3:0A:07:25:37:C9:42:4A:5B:76:77:50:E1\r\n X509v3 Certificate Policies: \r\n Policy: 1.3.6.1.4.1.6334.1.0\r\n CPS: http://www.public-trust.com/CPS/OmniRoot.html\r\n\r\n X509v3 Authority Key Identifier: \r\n DirName:/C=US/O=GTE Corporation/OU=GTE CyberTrust Solutions, Inc\r\n serial:01:A5\r\n\r\n X509v3 Key Usage: critical\r\n Certificate Sign, CRL Sign\r\n X509v3 Basic Constraints: critical\r\n CA:TRUE, pathlen:0\r\n Signature Algorithm: sha1WithRSAEncryption\r\n 43:b3:45:83:54:71:c4:1f:dc:b2:3c:6b:4e:bf:26:f2:4e:f2:\r\n ad:9a:5b:fa:86:37:88:e8:14:6c:41:18:42:5f:ef:65:3e:eb:\r\n 03:77:a0:b7:9e:75:7a:51:7c:bb:15:5b:b8:af:91:a0:34:92:\r\n 53:ed:7f:2a:49:84:ac:b9:80:4b:b5:c7:b2:23:22:fb:eb:d8:\r\n fb:6e:c9:3c:f3:d2:d1:bb:be:c9:1c:ff:6d:01:db:69:80:0e:\r\n 99:a5:ea:9e:7b:97:98:8f:b7:cf:22:9c:b3:b8:5d:e5:a9:33:\r\n 17:74:c6:97:37:0f:b4:e9:26:82:5f:61:0b:3f:1e:3d:64:e9:\r\n 2b:9b\r\n-----BEGIN CERTIFICATE-----\r\nMIIEQjCCA6ugAwIBAgIEBAAD+zANBgkqhkiG9w0BAQUFADB1MQswCQYDVQQGEwJV\r\nUzEYMBYGA1UEChMPR1RFIENvcnBvcmF0aW9uMScwJQYDVQQLEx5HVEUgQ3liZXJU\r\ncnVzdCBTb2x1dGlvbnMsIEluYy4xIzAhBgNVBAMTGkdURSBDeWJlclRydXN0IEds\r\nb2JhbCBSb290MB4XDTA2MDMxNDIwMzAwMFoXDTEzMDMxNDIzNTkwMFowXzELMAkG\r\nA1UEBhMCQkUxEzARBgNVBAoTCkN5YmVydHJ1c3QxFzAVBgNVBAsTDkVkdWNhdGlv\r\nbmFsIENBMSIwIAYDVQQDExlDeWJlcnRydXN0IEVkdWNhdGlvbmFsIENBMIIBIjAN\r\nBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQ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maXqnnuXmI+3zyKcs7hd5akzF3TGlzcPtOkmgl9hCz8ePWTpK5s=\r\n-----END CERTIFICATE-----\r\nCertificate:\r\n Data:\r\n Version: 1 (0x0)\r\n Serial Number: 421 (0x1a5)\r\n Signature Algorithm: md5WithRSAEncryption\r\n Issuer: C=US, O=GTE Corporation, OU=GTE CyberTrust Solutions, Inc., CN=GTE CyberTrust Global Root\r\n Validity\r\n Not Before: Aug 13 00:29:00 1998 GMT\r\n Not After : Aug 13 23:59:00 2018 GMT\r\n Subject: C=US, O=GTE Corporation, OU=GTE CyberTrust Solutions, Inc., CN=GTE CyberTrust Global Root\r\n Subject Public Key Info:\r\n Public Key Algorithm: rsaEncryption\r\n RSA Public Key: (1024 bit)\r\n Modulus (1024 bit):\r\n 00:95:0f:a0:b6:f0:50:9c:e8:7a:c7:88:cd:dd:17:\r\n 0e:2e:b0:94:d0:1b:3d:0e:f6:94:c0:8a:94:c7:06:\r\n c8:90:97:c8:b8:64:1a:7a:7e:6c:3c:53:e1:37:28:\r\n 73:60:7f:b2:97:53:07:9f:53:f9:6d:58:94:d2:af:\r\n 8d:6d:88:67:80:e6:ed:b2:95:cf:72:31:ca:a5:1c:\r\n 72:ba:5c:02:e7:64:42:e7:f9:a9:2c:d6:3a:0d:ac:\r\n 8d:42:aa:24:01:39:e6:9c:3f:01:85:57:0d:58:87:\r\n 45:f8:d3:85:aa:93:69:26:85:70:48:80:3f:12:15:\r\n c7:79:b4:1f:05:2f:3b:62:99\r\n Exponent: 65537 (0x10001)\r\n Signature Algorithm: md5WithRSAEncryption\r\n 6d:eb:1b:09:e9:5e:d9:51:db:67:22:61:a4:2a:3c:48:77:e3:\r\n a0:7c:a6:de:73:a2:14:03:85:3d:fb:ab:0e:30:c5:83:16:33:\r\n 81:13:08:9e:7b:34:4e:df:40:c8:74:d7:b9:7d:dc:f4:76:55:\r\n 7d:9b:63:54:18:e9:f0:ea:f3:5c:b1:d9:8b:42:1e:b9:c0:95:\r\n 4e:ba:fa:d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onelab) diff --git a/tools/upgrade-db.py b/tools/upgrade-db.py index 4c9d1d51..338c55c9 100755 --- a/tools/upgrade-db.py +++ b/tools/upgrade-db.py @@ -17,18 +17,18 @@ import pgdb config = {} config_file = "/etc/planetlab/plc_config" -execfile(config_file, config) +exec(compile(open(config_file).read(), config_file, 'exec'), config) upgrade_config_file = "plcdb.3-4.conf" schema_file = "planetlab4.sql" temp_dir = "/tmp" def usage(): - print "Usage: %s [OPTION] UPGRADE_CONFIG_FILE " % sys.argv[0] - print "Options:" - print " -s, --schema=FILE Upgraded Database Schema" - print " -t, --temp-dir=DIR Temp Directory" - print " --help This message" + print("Usage: %s [OPTION] UPGRADE_CONFIG_FILE " % sys.argv[0]) + print("Options:") + print(" -s, --schema=FILE Upgraded Database Schema") + print(" -t, --temp-dir=DIR Temp Directory") + print(" --help This message") sys.exit(1) try: @@ -37,8 +37,8 @@ try: ["schema=", "temp-dir=", "help"]) -except getopt.GetoptError, err: - print "Error: ", err.msg +except getopt.GetoptError as err: + print("Error: ", err.msg) usage() for (opt, optval) in opts: @@ -51,7 +51,7 @@ for (opt, optval) in opts: try: upgrade_config_file = argv[0] except IndexError: - print "Error: too few arguments" + print("Error: too few arguments") usage() schema = {} @@ -64,18 +64,18 @@ temp_tables = {} # load conf file for this upgrade try: upgrade_config = {} - execfile(upgrade_config_file, upgrade_config) + exec(compile(open(upgrade_config_file).read(), upgrade_config_file, 'exec'), upgrade_config) upgrade_config.pop('__builtins__') db_version_previous = upgrade_config['DB_VERSION_PREVIOUS'] db_version_new = upgrade_config['DB_VERSION_NEW'] -except IOError, fault: - print "Error: upgrade config file (%s) not found. Exiting" % \ - (fault) +except IOError as fault: + print("Error: upgrade config file (%s) not found. Exiting" % \ + (fault)) sys.exit(1) -except KeyError, fault: - print "Error: %s not set in upgrade confing (%s). Exiting" % \ - (fault, upgrade_config_file) +except KeyError as fault: + print("Error: %s not set in upgrade confing (%s). Exiting" % \ + (fault, upgrade_config_file)) sys.exit(1) @@ -94,7 +94,7 @@ def archive_db(database, archived_database): (archived_database, database, archived_database) exit_status = os.system(archive_db) if exit_status: - print "Error: unable to archive database. Upgrade failed" + print("Error: unable to archive database. Upgrade failed") sys.exit(1) #print "Status: %s has been archived. now named %s" % (database, archived_database) @@ -107,11 +107,11 @@ def encode_utf8(inputfile_name, outputfile_name): for line in inputfile: if line.upper().find('SET CLIENT_ENCODING') > -1: continue - outputfile.write(unicode(line, 'iso-8859-1').encode('utf8')) + outputfile.write(str(line, 'iso-8859-1').encode('utf8')) inputfile.close() outputfile.close() except: - print 'error encoding file' + print('error encoding file') raise def create_item_from_schema(item_name): @@ -122,14 +122,14 @@ def create_item_from_schema(item_name): (config['PLC_DB_NAME'], config['PLC_DB_USER'],"".join(body_list) ) ) if exit_status: raise Exception - except Exception, fault: - print 'Error: create %s failed. Check schema.' % item_name + except Exception as fault: + print('Error: create %s failed. Check schema.' % item_name) sys.exit(1) raise fault except KeyError: - print "Error: cannot create %s. definition not found in %s" % \ - (key, schema_file) + print("Error: cannot create %s. definition not found in %s" % \ + (key, schema_file)) return False def fix_row(row, table_name, table_fields): @@ -190,8 +190,8 @@ def generate_temp_table(table_name, db): table_fields.append(field_parts[0]) old_fields.append(field_parts[1]) if field_parts[2:]: - joins.update(set(filter(lambda x: not x.find('=') > -1, field_parts[2:]))) - wheres.update(set(filter(lambda x: x.find('=') > -1, field_parts[2:]))) + joins.update(set([x for x in field_parts[2:] if not x.find('=') > -1])) + wheres.update(set([x for x in field_parts[2:] if x.find('=') > -1])) # get indices of fields that cannot be null (type, body_list) = schema[table_name] @@ -234,7 +234,7 @@ def generate_temp_table(table_name, db): if row == None: continue # do not attempt to write rows with null primary keys - if filter(lambda x: row[x] == None, primary_key_indices): + if [x for x in primary_key_indices if row[x] == None]: continue for i in range(len(row)): # convert nulls into something pg can understand @@ -261,14 +261,14 @@ def generate_temp_table(table_name, db): #print "WARNING: cannot upgrade %s. upgrade def not found. skipping" % \ # (table_name) return False - except IndexError, fault: - print "Error: error found in upgrade config file. " \ + except IndexError as fault: + print("Error: error found in upgrade config file. " \ "check %s configuration. Aborting " % \ - (table_name) + (table_name)) sys.exit(1) except: - print "Error: configuration for %s doesnt match db schema. " \ - " Aborting" % (table_name) + print("Error: configuration for %s doesnt match db schema. " \ + " Aborting" % (table_name)) try: db.rollback() except: @@ -285,22 +285,22 @@ try: cursor.execute("SELECT relname from pg_class where relname = 'plc_db_version'") rows = cursor.fetchall() if not rows: - print "Warning: current db has no version. Unable to validate config file." + print("Warning: current db has no version. Unable to validate config file.") else: cursor.execute("SELECT version FROM plc_db_version") rows = cursor.fetchall() if not rows or not rows[0]: - print "Warning: current db has no version. Unable to validate config file." + print("Warning: current db has no version. Unable to validate config file.") elif rows[0][0] == db_version_new: - print "Status: Versions are the same. No upgrade necessary." + print("Status: Versions are the same. No upgrade necessary.") sys.exit() elif not rows[0][0] == db_version_previous: - print "Stauts: DB_VERSION_PREVIOUS in config file (%s) does not" \ - " match current db version %d" % (upgrade_config_file, rows[0][0]) + print("Stauts: DB_VERSION_PREVIOUS in config file (%s) does not" \ + " match current db version %d" % (upgrade_config_file, rows[0][0])) sys.exit() else: - print "STATUS: attempting upgrade from %d to %d" % \ - (db_version_previous, db_version_new) + print("STATUS: attempting upgrade from %d to %d" % \ + (db_version_previous, db_version_new)) # check db encoding sql = " SELECT pg_catalog.pg_encoding_to_char(d.encoding)" \ @@ -309,7 +309,7 @@ try: cursor.execute(sql) rows = cursor.fetchall() if rows[0][0] not in ['UTF8', 'UNICODE']: - print "WARNING: db encoding is not utf8. Attempting to encode" + print("WARNING: db encoding is not utf8. Attempting to encode") db.close() # generate db dump dump_file = '%s/dump.sql' % (temp_dir) @@ -317,10 +317,10 @@ try: dump_cmd = 'pg_dump -i %s -U postgres -f %s > /dev/null 2>&1' % \ (config['PLC_DB_NAME'], dump_file) if os.system(dump_cmd): - print "ERROR: during db dump. Exiting." + print("ERROR: during db dump. Exiting.") sys.exit(1) # encode dump to utf8 - print "Status: encoding database dump" + print("Status: encoding database dump") encode_utf8(dump_file, dump_file_encoded) # archive original db archive_db(config['PLC_DB_NAME'], config['PLC_DB_NAME']+'_sqlascii_archived') @@ -329,9 +329,9 @@ try: 'psql -a -U %s %s < %s > /dev/null 2>&1;' % \ (config['PLC_DB_NAME'], config['PLC_DB_USER'], \ config['PLC_DB_NAME'], dump_file_encoded) - print "Status: recreating database as utf8" + print("Status: recreating database as utf8") if os.system(recreate_cmd): - print "Error: database encoding failed. Aborting" + print("Error: database encoding failed. Aborting") sys.exit(1) os.remove(dump_file_encoded) @@ -382,7 +382,7 @@ try: break schema[item_name] = (item_type, fields) else: - print "Error: unknown type %s" % item_type + print("Error: unknown type %s" % item_type) elif line.startswith("INSERT"): inserts.append(line) index = index + 1 @@ -390,7 +390,7 @@ try: except: raise -print "Status: generating temp tables" +print("Status: generating temp tables") # generate all temp tables for key in schema_items_ordered: (type, body_list) = schema[key] @@ -401,18 +401,18 @@ for key in schema_items_ordered: cursor.close() db.close() -print "Status: archiving database" +print("Status: archiving database") archive_db(config['PLC_DB_NAME'], config['PLC_DB_NAME']+'_archived') os.system('createdb -U postgres -E UTF8 %s > /dev/null; ' % config['PLC_DB_NAME']) -print "Status: upgrading database" +print("Status: upgrading database") # attempt to create and load all items from schema into temp db try: for key in schema_items_ordered: (type, body_list) = schema[key] create_item_from_schema(key) if type == 'TABLE': - if upgrade_config.has_key(key): + if key in upgrade_config: # attempt to populate with temp table data table_def = upgrade_config[key].replace('(', '').replace(')', '').split(',') table_fields = [field.strip().split(':')[0] for field in table_def] @@ -422,10 +422,10 @@ try: ", ".join(table_fields), temp_tables[key] ) exit_status = os.system(insert_cmd) if exit_status: - print "Error: upgrade %s failed" % key + print("Error: upgrade %s failed" % key) sys.exit(1) # update the primary key sequence - if sequences.has_key(key): + if key in sequences: sequence = key +"_"+ sequences[key] +"_seq" update_seq = "psql %s %s -c " \ " \"select setval('%s', max(%s)) FROM %s;\" > /dev/null" % \ @@ -433,18 +433,18 @@ try: sequences[key], key) exit_status = os.system(update_seq) if exit_status: - print "Error: sequence %s update failed" % sequence + print("Error: sequence %s update failed" % sequence) sys.exit(1) else: # check if there are any insert stmts in schema for this table - print "Warning: %s has no temp data file. Unable to populate with old data" % key + print("Warning: %s has no temp data file. Unable to populate with old data" % key) for insert_stmt in inserts: if insert_stmt.find(key) > -1: insert_cmd = 'psql %s postgres -qc "%s;" > /dev/null 2>&1' % \ (config['PLC_DB_NAME'], insert_stmt) os.system(insert_cmd) except: - print "Error: failed to populate db. Unarchiving original database and aborting" + print("Error: failed to populate db. Unarchiving original database and aborting") undo_command = "dropdb -U postgres %s > /dev/null; psql template1 postgres -qc" \ " 'ALTER DATABASE %s RENAME TO %s;'; > /dev/null" % \ (config['PLC_DB_NAME'], config['PLC_DB_NAME']+'_archived', config['PLC_DB_NAME']) @@ -454,4 +454,4 @@ except: #remove_temp_tables() -print "upgrade complete" +print("upgrade complete") diff --git a/wsdl/api2wsdl.py b/wsdl/api2wsdl.py index 296048e4..d8f92874 100755 --- a/wsdl/api2wsdl.py +++ b/wsdl/api2wsdl.py @@ -145,5 +145,5 @@ add_wsdl_ports_and_bindings(wsdl) add_wsdl_service(wsdl) -print wsdl.toprettyxml() +print(wsdl.toprettyxml())