# 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:
#
# 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 = \
# 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):
# 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")
# Use our escape function
args = [self, value, write]
- if isinstance(value, (str, unicode)):
+ if isinstance(value, str):
args.append(xmlrpclib_escape)
try:
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
# You can't hide from me!
-xmlrpclib.Marshaller._Marshaller__dump = xmlrpclib_dump
+xmlrpc.client.Marshaller._Marshaller__dump = xmlrpclib_dump
# SOAP support is optional
try:
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"):
# 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:
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(
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]
# 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)
####################
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:
# 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]
# 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)
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
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)
", ".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)
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
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
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
# 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)
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
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
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]
# 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)
# 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
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
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):
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)
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)
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)
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)
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"
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)
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'])
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
", ".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)
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 + ", " + \
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":
if __name__ == '__main__':
import pprint
pprint = pprint.PrettyPrinter()
- pprint.pprint(Config().__dict__.items())
+ pprint.pprint(list(Config().__dict__.items()))
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
", ".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)
", ".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)
# 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):
# 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)
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'
sorts = []
clips = []
- for field, value in self.iteritems():
+ for field, value in self.items():
# handle negation, numeric comparisons
# simple, 1-depth only mechanism
'&' : 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)
# 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['|']:
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])))
# 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)):
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':
#
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
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
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
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
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
", ".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)
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
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)
", ".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)
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):
bytes[i] = "%02x" % byte
mac = ":".join(bytes)
except:
- raise PLCInvalidArgument, "Invalid MAC address %s"%mac
+ raise PLCInvalidArgument("Invalid MAC address %s"%mac)
return mac
return bwlimit
if bwlimit < 500000:
- raise PLCInvalidArgument, 'Minimum bw is 500 kbs'
+ raise PLCInvalidArgument('Minimum bw is 500 kbs')
return bwlimit
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
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']:
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
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!
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
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):
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)
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
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):
" 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
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):
"""
", ".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)
# Copyright (C) 2006 The Trustees of Princeton University
#
-import ldap
+from . import ldap
import traceback
from PLC.Debug import profile
from PLC.Faults import *
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):
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)
# 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]
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]
.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))
# 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)
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)
# Mark Huang <mlhuang@cs.princeton.edu>
# Copyright (C) 2006 The Trustees of Princeton University
#
-import xmlrpclib
+import xmlrpc.client
from types import *
import textwrap
import os
return result
- except PLCFault, fault:
+ except PLCFault as fault:
caller = ""
if isinstance(self.caller, Person):
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)
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)
# 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:
"""
# 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 = ()
try:
self.type_check(name, value, item, args)
return
- except PLCInvalidArgument, fault:
+ except PLCInvalidArgument as fault:
pass
raise fault
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)):
# 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:
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):
"""
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(),
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()
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']]}
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):
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(),
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()
# 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']:
# 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
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
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']
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):
roles = ['admin']
- initscript_fields = dict(filter(can_update, InitScript.fields.items()))
+ initscript_fields = dict(list(filter(can_update, list(InitScript.fields.items()))))
accepts = [
Auth(),
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()
# 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
# 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)
'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)
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
'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)
# 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]
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']
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:
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):
"""
roles = ['admin']
- nodegroup_fields = dict(filter(can_update, NodeGroup.fields.items()))
+ nodegroup_fields = dict(list(filter(can_update, list(NodeGroup.fields.items()))))
accepts = [
Auth(),
# 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,
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
'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)
# 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']:
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)
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']
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(),
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']
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):
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(),
# 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()
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):
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(),
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']]}
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):
roles = ['admin']
- peer_fields = dict(filter(can_update, Peer.fields.items()))
+ peer_fields = dict(list(filter(can_update, list(Peer.fields.items()))))
accepts = [
Auth(),
# 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
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:
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):
"""
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(),
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)
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
'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)
# 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)
# 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)
# 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)
# 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
# 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)
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)
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']
roles = ['admin']
- site_fields = dict(filter(can_update, Site.fields.items()))
+ site_fields = dict(list(filter(can_update, list(Site.fields.items()))))
accepts = [
Auth(),
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()
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']
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(),
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)
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
'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)
# 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
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']
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)
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
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):
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']
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']]}
# 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,
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)
# 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)
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):
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(),
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()
# 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]
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)
# 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
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] = ""
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']
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()),
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
# 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)
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']:
# 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()
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']]}
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']],
(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)
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()
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()
# 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
# 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
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]
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']]
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()
# 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
# 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()
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']
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
# 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()
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()
# 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'])
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()
# 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()
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()
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()
# 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.
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']
# 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]
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
# 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]
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']
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
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()
# 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()
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()
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()
# 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()
# 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()
# 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)
# 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)
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']
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
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()
# 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)
# 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
# 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)
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()
# 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()
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']
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
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']]}
# 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
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)
# 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)
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()
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']
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']
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()
# 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
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
# 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
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))
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))
# 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))
# 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
# 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']
# 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:
# 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)
# 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)
]
# 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):
# 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).
# 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:
matchers = {}
result = {}
- for field in regexps.keys():
+ for field in list(regexps.keys()):
matchers[field] = re.compile(regexps[field])
result[field]={}
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
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)
# 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']
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
# 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()
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()
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 = []
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
# 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:
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.,
# 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:
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):
# 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
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
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()
# 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
# 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]
# 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)
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,
# 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}
'hostname': node['hostname'],
'interfaces': interfaces,
'groups': groups,
- 'conf_files': conf_files.values(),
+ 'conf_files': list(conf_files.values()),
'initscripts': initscripts,
'slivers': slivers,
'accounts': accounts,
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,
# 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]
# 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
try:
udp_pod(host, session)
- except socket.error, e:
+ except socket.error as e:
# Ignore socket errors
pass
# 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
# 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'])
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
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))
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
# 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']
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"
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])
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}"
# 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
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)
# 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
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}"
# 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)
# 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
# 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)
# 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
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']))
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)
# 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
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']))
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)
# 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:
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]
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]
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]
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
import random
import base64
import time
-import urllib
+import urllib.request, urllib.parse, urllib.error
from types import StringTypes
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)))
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
# 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))
'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']}
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
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):
"""
# 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
# 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)
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
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)
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('/>')
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()
# <slice name="site_slice" id="12345" expiry="1138712648">
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']))})
# <nodes>
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]
# <node id="12345" hostname="node.site.domain"/>
xml.simpleElement('node',
{'id': str(node['node_id']),
- 'hostname': unicode(node['hostname'])})
+ 'hostname': str(node['hostname'])})
# </nodes>
xml.endElement('nodes')
# <users>
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]
# <user person_id="12345" email="user@site.domain"/>
xml.simpleElement('user',
- {'person_id': unicode(user['person_id']),
- 'email': unicode(user['email'])})
+ {'person_id': str(user['person_id']),
+ 'email': str(user['email'])})
# </users>
xml.endElement('users')
# <rspec>
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]
type = "string"
# <resource name="tag_type">
- xml.startElement('resource', {'name': unicode(attribute_name)})
+ xml.startElement('resource', {'name': str(attribute_name)})
# <value name="element_name" type="element_type">
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))
# </value>
xml.endElement('value', indent = False)
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()
ticket.close()
if rc:
- raise PLCAPIError, err
+ raise PLCAPIError(err)
return signed_ticket
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
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:
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]
# 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]
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)
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']
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(),
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()
# 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
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):
"""
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(),
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)
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):
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(),
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)
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]
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()
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):
roles = ['admin']
- initscript_fields = dict(filter(can_update, InitScript.fields.items()))
+ initscript_fields = dict(list(filter(can_update, list(InitScript.fields.items()))))
accepts = [
Auth(),
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)
# 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]
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)
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
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']
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
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):
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(),
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()
# 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
-from __future__ import print_function
+
from PLC.Faults import *
from PLC.Method import Method
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):
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(),
# 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:
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))
# 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}
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):
roles = ['admin']
- message_fields = dict(filter(can_update, Message.fields.items()))
+ message_fields = dict(list(filter(can_update, list(Message.fields.items()))))
accepts = [
Auth(),
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)
# 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
# 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)
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:
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
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):
"""
roles = ['admin']
- nodegroup_fields = dict(filter(can_update, NodeGroup.fields.items()))
+ nodegroup_fields = dict(list(filter(can_update, list(NodeGroup.fields.items()))))
accepts = [
Auth(),
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)
# 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
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']
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
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):
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(),
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)
# 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
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):
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(),
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)
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):
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(),
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)
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):
roles = ['admin']
- peer_fields = dict(filter(can_update, Peer.fields.items()))
+ peer_fields = dict(list(filter(can_update, list(Peer.fields.items()))))
accepts = [
Auth(),
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()
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
# 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
# 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)
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:
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'
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']
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
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'] + \
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(),
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
# 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':
# 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:
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']
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
# 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
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
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)
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']
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']
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
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):
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(),
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)
import random
import base64
import time
-import urllib
+import urllib.request, urllib.parse, urllib.error
from PLC.Logger import logger
from PLC.Faults import *
# 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'])
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)))
# 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))
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
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]
'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'],
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
#!/usr/bin/python -tt
-from __future__ import print_function
+
import os
import glob
from PLC.Parameter import Parameter, Mixed
from PLC.Method import Method, xmlrpc_type
+from functools import reduce
class methodSignature(Method):
"""
import sys
-import xmlrpclib
+import xmlrpc.client
from PLC.Parameter import Parameter, Mixed
from PLC.Method import 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
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
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
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
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)
", ".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)
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
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
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)
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
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
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)
# 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
", ".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)
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
# 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')
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):
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)
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
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']
", ".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)
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)
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)
# 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)
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
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
(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
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)
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):
"""
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)
", ".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)
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
# 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:
# 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:
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)
# 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:
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)
import types
from types import StringTypes, NoneType
import traceback
-import commands
+import subprocess
import re
from pprint import pformat
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
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 " + \
# 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
"""
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 = {}
#
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
response = self.body
self.body = ""
errmsg="<no known 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()
# 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
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)
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))
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
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:
import os
import pydoc
-import xmlrpclib
+import xmlrpc.client
from PLC.API import PLCAPI
from PLC.Parameter import Mixed
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:
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)
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) + \
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
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()
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,
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
def begin(self):
if self.calls:
- raise Exception, "multicall already in progress"
+ raise Exception("multicall already in progress")
self.multi = True
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
", ".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)
def validate_name(self, name):
if not len(name):
- raise PLCInvalidArgument, "Name must be specified"
+ raise PLCInvalidArgument("Name must be specified")
return name
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
# 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:
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)
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)
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
", ".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)
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
# 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:
# 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:
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:
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']
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)
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:
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)
# 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)
"""
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):
"""
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)
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)" % \
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) ] )
"""
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
@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
# 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
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
"""
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
@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()
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:
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))
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
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
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)
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()
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
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
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)
s.close()
if rejected:
- raise PLCAPIError, "Error sending message to " + ", ".join(rejected.keys())
+ raise PLCAPIError("Error sending message to " + ", ".join(list(rejected.keys())))
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.
"""
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()
</body></html>
""")
-class PLCAPIServer(BaseHTTPServer.HTTPServer):
+class PLCAPIServer(http.server.HTTPServer):
"""
Simple standalone HTTP server for testing PLCAPI.
"""
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"
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:
import sys
import time
import traceback
-import xmlrpclib
+import xmlrpc.client
from mod_python import apache
from PLC.Logger import logger
import sys
import traceback
-import xmlrpclib
+import xmlrpc.client
from mod_python import apache
from PLC.Logger import logger
return apache.OK
- except Exception, err:
+ except Exception as err:
logger.exception("INTERNAL ERROR !!")
return apache.HTTP_INTERNAL_SERVER_ERROR
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):
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)
@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)
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'
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, "", "", "")
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):
returns.appendChild(paramElement(None, func.returns))
section.appendChild(returns)
- print section.toprettyxml(encoding = "UTF-8")
+ print(section.toprettyxml(encoding = "UTF-8"))
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:
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
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)
# 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
'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']
'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']
'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']
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+DQojICAgIGJpbmRzY3JpcHQNCiMNCiMgPEF1dGhvcj4NCiMgICAgSmVmZnJ5IEpvaG5zdG9uIGFuZCBKZXJlbXkgUGxpY2h0YQ0KIw0KIyA8UHVycG9zZT4NCiMgICAgRG93bmxvYWRzIGFuZCBpbnN0YWxscyBzdG9yayBvbiBhIG5vZGUuDQoNCiMgc2F2ZSBvcmlnaW5hbCBQV0QNCk9MRFBXRD0kUFdEDQoNCiMgZXJyb3IgcmVwb3J0aW5nIGZ1bmN0aW9uDQplcnJvcigpDQp7DQogICBlY2hvDQogICBlY2hvICJQbGVhc2UgRS1tYWlsIHN0b3JrLXN1cHBvcnRAY3MuYXJpem9uYS5lZHUgaWYgeW91IGJlbGlldmUgeW91IGhhdmUiIA0KICAgZWNobyAicmVjZWl2ZWQgdGhpcyBtZXNzYWdlIGluIGVycm9yLiINCg0KICAgIyBnZXQgcmlkIG9mIENFUlQgZmlsZQ0KICAgaWYgWyAtZiAkQ0VSVCBdDQogICB0aGVuDQogICAgICBybSAtZiAkQ0VSVCA+IC9kZXYvbnVsbA0KICAgZmkNCg0KICAgIyByZXN0b3JlIG9yaWdpbmFsIFBXRA0KICAgY2QgJE9MRFBXRA0KICAgZXhpdCAxDQp9DQoNCkNFUlQ9YHB3ZGAvdGVtcGNydGZpbGUNCg0KI2Z1bmN0aW9ucw0KDQojIyMNCiMjIyBjcmVhdGVDZXJ0aWZpY2F0ZSgpDQojIyMgICAgcHJpbnRzIG91dCB0aGUgZXF1aWZheCBjZXJ0aW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AtZiAkQ0VSVCA+IC9kZXYvbnVsbA0KZWxzZQ0KICAgZWNobw0KICAgZWNobyAiQW4gZXJyb3Igb2NjdXJyZWQgZHVyaW5nIGluc3RhbGwgZmluYWxpemF0aW9uLi4uICBQbGVhc2UgY29udGFjdCINCiAgIGVjaG8gInN0b3JrLXN1cHBvcnRAY3MuYXJpem9uYS5lZHUgZm9yIGFzc2lzdGFuY2UuIg0KICAgI3JtIC1mICRDRVJUID4gL2Rldi9udWxsDQogICBleGl0IDENCmZpDQoNCiMgZG9uZQ0KZXhpdCAwDQo=', 'name': 'arizona_stork_2', 'encoding': 'base64'}, {'initscript_id': 9, 'script': 'IyEvYmluL2Jhc2gNCmNkIC8NCnJtIC1mIHN0YXJ0X3B1cnBsZQ0Kd2dldCBodHRwOi8vd3d3LmNzLnByaW5jZXRvbi5lZHUvfmRlaXNlbnN0L3B1cnBsZS9zdGFydF9wdXJwbGUNCmNobW9kIDc1NSBzdGFydF9wdXJwbGUNCnN1IHByaW5jZXRvbl9wdXJwbGUgLWMgJy4vc3RhcnRfcHVycGxlJw0K', 'name': 'princeton_purple', 'encoding': 'base64'}, {'initscript_id': 6, 'script': 'IyEgL2Jpbi9zaA0KDQojIHNhdmUgb3JpZ2luYWwgUFdEDQpPTERQV0Q9JFBXRA0KDQojIGVycm9yIHJlcG9ydGluZyBmdW5jdGlvbg0KZXJyb3IoKQ0Kew0KICAgZWNobw0KICAgZWNobyAiUGxlYXNlIEUtbWFpbCBzdG9yay1zdXBwb3J0QGNzLmFyaXpvbmEuZWR1IGlmIHlvdSBiZWxpZXZlIHlvdSBoYXZlIiANCiAgIGVjaG8gInJlY2VpdmVkIHRoaXMgbWVzc2FnZSBpbiBlcnJvci4iDQoNCiAgICMgcmVzdG9yZSBvcmlnaW5hbCBQV0QNCiAgIGNkICRPTERQV0QNCiAgIGV4aXQgMQ0KfQ0KDQojIGNoZWNrIGZvciByb290IHVzZXINCmlmIFsgJFVJRCAtbmUgIjAiIF0NCnRoZW4N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gIiovNSAqICogKiAqIC91c3IvYmluL2N1cmwgLXMgaHR0cDovLyRTRVJWRVIvIiB8IGNyb250YWIgLQ0KL3NiaW4vY2hrY29uZmlnIGNyb25kIG9uDQo=', 'name': 'princeton_hello', 'encoding': 'base64'}]])
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'])
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.4.5 (GNU/Linux)\n\nmQGiBEW0kJMRBACaTlrW0eYlQwkzRuMFfEYMwyqBT9Bm6R4g68SJ5GdjCRu3XCnd\nGTGCFF4ewOu6IcUmZDv39eqxShBWyx+JqBogYPGNvPrj07jXXKaSBCM7TPk+9kMW\nPziIxSClvO15XaPKv89c6kFaEBe0z1xsoMB/TNoLmhFUxmc24O7JnEqmYwCgjzIS\nHP7u9KIOYk1ZlTdOtwyRxVkD/1uYbPzD0Qigf8uF9ADzx7I4F1ATd2ezYq0EfzhD\nTDa15FPWwA7jm+Mye//ovT01Ju6JQtCU4N9wRsV2Yy2tWcWFZiYt+BISPVS0lJDx\nQ2Cd2+kEWyl9ByL9/ACHmCUz0OOaz9j1x+GpJLArjUdZSJOs68kPw90F62mrLHfg\nYCHpA/0ZcdJQG9QYNZ67KMFqNPho+uRww5/7kxQ4wkSyP7EK3QUVgXG5OWZ/1mPZ\njon9N04nnjrL9qoQv7m04ih3rmqyGy1MsicNCoys0RNh1eavPdAsXD1ZEXnWPA7z\naC37hxUaRPP3hH+1ifjPpAWQX1E89MK2y2zQpZipvEOAO2Lw8LRCT25lTGFiIENl\nbnRyYWwgKGh0dHA6Ly9vbmVsYWItcGxjLmlucmlhLmZyLykgPHN1cHBvc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zSqinohParWaHv+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\nUzEYMBYGA1UEChMPR1RFIENvc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dU\r\nRSBDb3Jwb3JhdGlvbjEnMCUGA1UECxMeR1RFIEN5YmVyVHJ1c3QgU29sdXRpb25z\r\nLCBJbmMuMSMwIQYDVQQDExpHVEUgQ3liZXJUcnVzdCBHbG9iYWwgUm9vdIICAaUw\r\nDgYDVR0PAQH/BAQDAgEGMBIGA1UdEwEB/wQIMAYBAf8CAQAwDQYJKoZIhvcNAQEF\r\nBQADgYEAQ7NFg1RxxB/csjxrTr8m8k7yrZpb+oY3iOgUbEEYQl/vZT7rA3egt551\r\nelF8uxVbuK+RoDSSU+1/KkmErLmAS7XHsiMi++vY+27JPPPS0bu+yRz/bQHbaYAO\r\nmaXqnnuXmI+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: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/', 'key': '-----BEGIN PGP PUBLIC KEY BLOCK-----\nVersion: GnuPG v1.4.5 (GNU/Linux)\n\nmQGiBEW0kJMRBACaTlrW0eYlQwkzRuMFfEYMwyqBT9Bm6R4g68SJ5GdjCRu3XCnd\nGTGCFF4ewOu6IcUmZDv39eqxShBWyx+JqBogYPGNvPrj07jXXKaSBCM7TPk+9kMW\nPziIxSClvO15XaPKv89c6kFaEBe0z1xsoMB/TNoLmhFUxmc24O7JnEqmYwCgjzIS\nHP7u9KIOYk1ZlTdOtwyRxVkD/1uYbPzD0Qigf8uF9ADzx7I4F1ATd2ezYq0EfzhD\nTDa15FPWwA7jm+Mye//ovT01Ju6JQtCU4N9wRsV2Yy2tWcWFZiYt+BISPVS0lJDx\nQ2Cd2+kEWyl9ByL9/ACHmCUz0OOaz9j1x+GpJLArjUdZSJOs68kPw90F62mrLHfg\nYCHpA/0ZcdJQG9QYNZ67KMFqNPho+uRww5/7kxQ4wkSyP7EK3QUVgXG5OWZ/1mPZ\njon9N04nnjrL9qoQv7m04ih3rmqyGy1MsicNCoys0RNh1eavPdAsXD1ZEXnWPA7z\naC37hxUaRPP3hH+1ifjPpAWQX1E89MK2y2zQpZipvEOAO2Lw8LRCT25lTGFiIENl\nbnRyYWwgKG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iEkEGBECAAkFAkW0kJQCGwwACgkQbruxNL8x\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+zANBgkqhkiG9w0BAQUF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gYEwf6F5pHcwdTELMAkGA1UEBhMCVVMxGDAWBgNVBAoTD0dU\r\nRSBDb3Jwb3JhdGlvbjEnMCUGA1UECxMeR1RFIEN5YmVyVHJ1c3QgU29sdXRpb25z\r\nLCBJbmMuMSMwIQYDVQQDExpHVEUgQ3liZXJUcnVzdCBHbG9iYWwgUm9vdIICAaUw\r\nDgYDVR0PAQH/BAQDAgEGMBIGA1UdEwEB/wQIMAYBAf8CAQAwDQYJKoZIhvcNAQEF\r\nBQADgYEAQ7NFg1RxxB/csjxrTr8m8k7yrZpb+oY3iOgUbEEYQl/vZT7rA3egt551\r\nelF8uxVbuK+RoDSSU+1/KkmErLmAS7XHsiMi++vY+27JPPPS0bu+yRz/bQHbaYAO\r\nmaXqnnuXmI+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: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'}
AddPeer(onelab)
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:
["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:
try:
upgrade_config_file = argv[0]
except IndexError:
- print "Error: too few arguments"
+ print("Error: too few arguments")
usage()
schema = {}
# 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)
(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)
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):
(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):
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]
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
#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:
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)" \
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)
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')
'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)
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
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]
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]
", ".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" % \
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'])
#remove_temp_tables()
-print "upgrade complete"
+print("upgrade complete")
add_wsdl_service(wsdl)
-print wsdl.toprettyxml()
+print(wsdl.toprettyxml())