From 63afad28e5b0a1d996c7912c5362e460588c879f Mon Sep 17 00:00:00 2001 From: Thierry Parmentelat Date: Mon, 3 Sep 2012 14:31:25 +0200 Subject: [PATCH] dos2unix --- sfa/util/enumeration.py | 70 ++--- sfa/util/faults.py | 664 ++++++++++++++++++++-------------------- sfa/util/genicode.py | 90 +++--- sfa/util/sfalogging.py | 402 ++++++++++++------------ sfa/util/sfatime.py | 132 ++++---- sfa/util/xrn.py | 536 ++++++++++++++++---------------- 6 files changed, 947 insertions(+), 947 deletions(-) diff --git a/sfa/util/enumeration.py b/sfa/util/enumeration.py index bea2ce98..b65508f8 100644 --- a/sfa/util/enumeration.py +++ b/sfa/util/enumeration.py @@ -1,35 +1,35 @@ -#---------------------------------------------------------------------- -# Copyright (c) 2008 Board of Trustees, Princeton University -# -# Permission is hereby granted, free of charge, to any person obtaining -# a copy of this software and/or hardware specification (the "Work") to -# deal in the Work without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, -# and/or sell copies of the Work, and to permit persons to whom the Work -# is furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be -# included in all copies or substantial portions of the Work. -# -# THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS -# IN THE WORK. -#---------------------------------------------------------------------- - -class Enum(set): - def __init__(self, *args, **kwds): - set.__init__(self) - enums = dict(zip(args, [object() for i in range(len(args))]), **kwds) - for (key, value) in enums.items(): - setattr(self, key, value) - self.add(eval('self.%s' % key)) - - -#def Enum2(*args, **kwds): -# enums = dict(zip(sequential, range(len(sequential))), **named) -# return type('Enum', (), enums) +#---------------------------------------------------------------------- +# Copyright (c) 2008 Board of Trustees, Princeton University +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and/or hardware specification (the "Work") to +# deal in the Work without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, +# and/or sell copies of the Work, and to permit persons to whom the Work +# is furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Work. +# +# THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS +# IN THE WORK. +#---------------------------------------------------------------------- + +class Enum(set): + def __init__(self, *args, **kwds): + set.__init__(self) + enums = dict(zip(args, [object() for i in range(len(args))]), **kwds) + for (key, value) in enums.items(): + setattr(self, key, value) + self.add(eval('self.%s' % key)) + + +#def Enum2(*args, **kwds): +# enums = dict(zip(sequential, range(len(sequential))), **named) +# return type('Enum', (), enums) diff --git a/sfa/util/faults.py b/sfa/util/faults.py index 848d8182..1dd8131b 100644 --- a/sfa/util/faults.py +++ b/sfa/util/faults.py @@ -1,332 +1,332 @@ -#---------------------------------------------------------------------- -# Copyright (c) 2008 Board of Trustees, Princeton University -# -# Permission is hereby granted, free of charge, to any person obtaining -# a copy of this software and/or hardware specification (the "Work") to -# deal in the Work without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, -# and/or sell copies of the Work, and to permit persons to whom the Work -# is furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be -# included in all copies or substantial portions of the Work. -# -# THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS -# IN THE WORK. -#---------------------------------------------------------------------- -# -# SFA API faults -# - -import xmlrpclib -from sfa.util.genicode import GENICODE - -class SfaFault(xmlrpclib.Fault): - def __init__(self, faultCode, faultString, extra = None): - if extra: - faultString += ": " + str(extra) - xmlrpclib.Fault.__init__(self, faultCode, faultString) - -class SfaInvalidAPIMethod(SfaFault): - def __init__(self, method, interface = None, extra = None): - faultString = "Invalid method " + method - if interface: - faultString += " for interface " + interface - SfaFault.__init__(self, GENICODE.UNSUPPORTED, faultString, extra) - -class SfaInvalidArgumentCount(SfaFault): - def __init__(self, got, min, max = min, extra = None): - if min != max: - expected = "%d-%d" % (min, max) - else: - expected = "%d" % min - faultString = "Expected %s arguments, got %d" % \ - (expected, got) - SfaFault.__init__(self, GENICODE.BADARGS, faultString, extra) - -class SfaInvalidArgument(SfaFault): - def __init__(self, extra = None, name = None): - if name is not None: - faultString = "Invalid %s value" % name - else: - faultString = "Invalid argument" - SfaFault.__init__(self, GENICODE.BADARGS, faultString, extra) - -class SfaAuthenticationFailure(SfaFault): - def __init__(self, extra = None): - faultString = "Failed to authenticate call" - SfaFault.__init__(self, GENICODE.ERROR, faultString, extra) - -class SfaDBError(SfaFault): - def __init__(self, extra = None): - faultString = "Database error" - SfaFault.__init__(self, GENICODE.DBERROR, faultString, extra) - -class SfaPermissionDenied(SfaFault): - def __init__(self, extra = None): - faultString = "Permission denied" - SfaFault.__init__(self, GENICODE.FORBIDDEN, faultString, extra) - -class SfaNotImplemented(SfaFault): - def __init__(self, interface=None, extra = None): - faultString = "Not implemented" - if interface: - faultString += " at interface " + interface - SfaFault.__init__(self, GENICODE.UNSUPPORTED, faultString, extra) - -class SfaAPIError(SfaFault): - def __init__(self, extra = None): - faultString = "Internal API error" - SfaFault.__init__(self, GENICODE.SERVERERROR, faultString, extra) - -class MalformedHrnException(SfaFault): - def __init__(self, value, extra = None): - self.value = value - faultString = "Malformed HRN: %(value)s" % locals() - SfaFault.__init__(self, GENICODE.ERROR, extra) - def __str__(self): - return repr(self.value) - -class TreeException(SfaFault): - def __init__(self, value, extra = None): - self.value = value - faultString = "Tree Exception: %(value)s, " % locals() - SfaFault.__init__(self, GENICODE.ERROR, faultString, extra) - def __str__(self): - return repr(self.value) - -class NonExistingRecord(SfaFault): - def __init__(self, value, extra = None): - self.value = value - faultString = "Non exsiting record %(value)s, " % locals() - SfaFault.__init__(self, GENICODE.SEARCHFAILED, faultString, extra) - def __str__(self): - return repr(self.value) - -class ExistingRecord(SfaFault): - def __init__(self, value, extra = None): - self.value = value - faultString = "Existing record: %(value)s, " % locals() - SfaFault.__init__(self, GENICODE.REFUSED, faultString, extra) - def __str__(self): - return repr(self.value) - - -class InvalidRPCParams(SfaFault): - def __init__(self, value, extra = None): - self.value = value - faultString = "Invalid RPC Params: %(value)s, " % locals() - SfaFault.__init__(self, GENICODE.RPCERROR, faultString, extra) - def __str__(self): - return repr(self.value) - -# SMBAKER exceptions follow - -class ConnectionKeyGIDMismatch(SfaFault): - def __init__(self, value, extra = None): - self.value = value - faultString = "Connection Key GID mismatch: %(value)s" % locals() - SfaFault.__init__(self, GENICODE.ERROR, faultString, extra) - def __str__(self): - return repr(self.value) - -class MissingCallerGID(SfaFault): - def __init__(self, value, extra = None): - self.value = value - faultString = "Missing Caller GID: %(value)s" % locals() - SfaFault.__init__(self, GENICODE.ERROR, faultString, extra) - def __str__(self): - return repr(self.value) - -class RecordNotFound(SfaFault): - def __init__(self, value, extra = None): - self.value = value - faultString = "Record not found: %(value)s" % locals() - SfaFault.__init__(self, GENICODE.ERROR, faultString, extra) - def __str__(self): - return repr(self.value) - -class UnknownSfaType(SfaFault): - def __init__(self, value, extra = None): - self.value = value - faultString = "Unknown SFA Type: %(value)s" % locals() - SfaFault.__init__(self, GENICODE.ERROR, faultString, extra) - def __str__(self): - return repr(self.value) - -class MissingAuthority(SfaFault): - def __init__(self, value, extra = None): - self.value = value - faultString = "Missing authority: %(value)s" % locals() - SfaFault.__init__(self, GENICODE.ERROR, faultString, extra) - def __str__(self): - return repr(self.value) - -class PlanetLabRecordDoesNotExist(SfaFault): - def __init__(self, value, extra = None): - self.value = value - faultString = "PlanetLab record does not exist : %(value)s" % locals() - SfaFault.__init__(self, GENICODE.ERROR, faultString, extra) - def __str__(self): - return repr(self.value) - -class PermissionError(SfaFault): - def __init__(self, value, extra = None): - self.value = value - faultString = "Permission error: %(value)s" % locals() - SfaFault.__init__(self, GENICODE.FORBIDDEN, faultString, extra) - def __str__(self): - return repr(self.value) - -class InsufficientRights(SfaFault): - def __init__(self, value, extra = None): - self.value = value - faultString = "Insufficient rights: %(value)s" % locals() - SfaFault.__init__(self, GENICODE.FORBIDDEN, faultString, extra) - def __str__(self): - return repr(self.value) - -class MissingDelegateBit(SfaFault): - def __init__(self, value, extra = None): - self.value = value - faultString = "Missing delegate bit: %(value)s" % locals() - SfaFault.__init__(self, GENICODE.FORBIDDEN, faultString, extra) - def __str__(self): - return repr(self.value) - -class ChildRightsNotSubsetOfParent(SfaFault): - def __init__(self, value, extra = None): - self.value = value - faultString = "Child rights not subset of parent: %(value)s" % locals() - SfaFault.__init__(self, GENICODE.FORBIDDEN, faultString, extra) - def __str__(self): - return repr(self.value) - -class CertMissingParent(SfaFault): - def __init__(self, value, extra = None): - self.value = value - faultString = "Cert missing parent: %(value)s" % locals() - SfaFault.__init__(self, GENICODE.ERROR, faultString, extra) - def __str__(self): - return repr(self.value) - -class CertNotSignedByParent(SfaFault): - def __init__(self, value, extra = None): - self.value = value - faultString = "Cert not signed by parent: %(value)s" % locals() - SfaFault.__init__(self, GENICODE.ERROR, faultString, extra) - def __str__(self): - return repr(self.value) - -class GidParentHrn(SfaFault): - def __init__(self, value, extra = None): - self.value = value - faultString = "Cert URN is not an extension of its parent: %(value)s" % locals() - SfaFault.__init__(self, GENICODE.ERROR, faultString, extra) - def __str__(self): - return repr(self.value) - -class GidInvalidParentHrn(SfaFault): - def __init__(self, value, extra = None): - self.value = value - faultString = "GID invalid parent hrn: %(value)s" % locals() - SfaFault.__init__(self, GENICODE.ERROR, faultString, extra) - def __str__(self): - return repr(self.value) - -class SliverDoesNotExist(SfaFault): - def __init__(self, value, extra = None): - self.value = value - faultString = "Sliver does not exist : %(value)s" % locals() - SfaFault.__init__(self, GENICODE.ERROR, faultString, extra) - def __str__(self): - return repr(self.value) - -class BadRequestHash(xmlrpclib.Fault): - def __init__(self, hash = None, extra = None): - faultString = "bad request hash: " + str(hash) - xmlrpclib.Fault.__init__(self, GENICODE.ERROR, faultString) - -class MissingTrustedRoots(SfaFault): - def __init__(self, value, extra = None): - self.value = value - faultString = "Trusted root directory does not exist: %(value)s" % locals() - SfaFault.__init__(self, GENICODE.SERVERERROR, faultString, extra) - def __str__(self): - return repr(self.value) - -class MissingSfaInfo(SfaFault): - def __init__(self, value, extra = None): - self.value = value - faultString = "Missing information: %(value)s" % locals() - SfaFault.__init__(self, GENICODE.ERROR, faultString, extra) - def __str__(self): - return repr(self.value) - -class InvalidRSpec(SfaFault): - def __init__(self, value, extra = None): - self.value = value - faultString = "Invalid RSpec: %(value)s" % locals() - SfaFault.__init__(self, GENICODE.ERROR, faultString, extra) - def __str__(self): - return repr(self.value) - -class InvalidRSpecVersion(SfaFault): - def __init__(self, value, extra = None): - self.value = value - faultString = "Invalid RSpec version: %(value)s" % locals() - SfaFault.__init__(self, GENICODE.BADVERSION, faultString, extra) - def __str__(self): - return repr(self.value) - -class UnsupportedRSpecVersion(SfaFault): - def __init__(self, value, extra = None): - self.value = value - faultString = "Unsupported RSpec version: %(value)s" % locals() - SfaFault.__init__(self, GENICODE.UNSUPPORTED, faultString, extra) - def __str__(self): - return repr(self.value) - -class InvalidRSpecElement(SfaFault): - def __init__(self, value, extra = None): - self.value = value - faultString = "Invalid RSpec Element: %(value)s" % locals() - SfaFault.__init__(self, GENICODE.ERROR, faultString, extra) - def __str__(self): - return repr(self.value) - -class InvalidXML(SfaFault): - def __init__(self, value, extra = None): - self.value = value - faultString = "Invalid XML Document: %(value)s" % locals() - SfaFault.__init__(self, GENICODE.ERROR, faultString, extra) - def __str__(self): - return repr(self.value) - -class AccountNotEnabled(SfaFault): - def __init__(self, extra = None): - faultString = "Account Disabled" - SfaFault.__init__(self, GENICODE.ERROR, faultString, extra) - def __str__(self): - return repr(self.value) - -class CredentialNotVerifiable(SfaFault): - def __init__(self, value, extra = None): - self.value = value - faultString = "Unable to verify credential: %(value)s, " %locals() - SfaFault.__init__(self, GENICODE.ERROR, faultString, extra) - def __str__(self): - return repr(self.value) - -class CertExpired(SfaFault): - def __init__(self, value, extra=None): - self.value = value - faultString = "%s cert is expired" % value - SfaFault.__init__(self, GENICODE.ERROR, faultString, extra) - +#---------------------------------------------------------------------- +# Copyright (c) 2008 Board of Trustees, Princeton University +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and/or hardware specification (the "Work") to +# deal in the Work without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, +# and/or sell copies of the Work, and to permit persons to whom the Work +# is furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Work. +# +# THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS +# IN THE WORK. +#---------------------------------------------------------------------- +# +# SFA API faults +# + +import xmlrpclib +from sfa.util.genicode import GENICODE + +class SfaFault(xmlrpclib.Fault): + def __init__(self, faultCode, faultString, extra = None): + if extra: + faultString += ": " + str(extra) + xmlrpclib.Fault.__init__(self, faultCode, faultString) + +class SfaInvalidAPIMethod(SfaFault): + def __init__(self, method, interface = None, extra = None): + faultString = "Invalid method " + method + if interface: + faultString += " for interface " + interface + SfaFault.__init__(self, GENICODE.UNSUPPORTED, faultString, extra) + +class SfaInvalidArgumentCount(SfaFault): + def __init__(self, got, min, max = min, extra = None): + if min != max: + expected = "%d-%d" % (min, max) + else: + expected = "%d" % min + faultString = "Expected %s arguments, got %d" % \ + (expected, got) + SfaFault.__init__(self, GENICODE.BADARGS, faultString, extra) + +class SfaInvalidArgument(SfaFault): + def __init__(self, extra = None, name = None): + if name is not None: + faultString = "Invalid %s value" % name + else: + faultString = "Invalid argument" + SfaFault.__init__(self, GENICODE.BADARGS, faultString, extra) + +class SfaAuthenticationFailure(SfaFault): + def __init__(self, extra = None): + faultString = "Failed to authenticate call" + SfaFault.__init__(self, GENICODE.ERROR, faultString, extra) + +class SfaDBError(SfaFault): + def __init__(self, extra = None): + faultString = "Database error" + SfaFault.__init__(self, GENICODE.DBERROR, faultString, extra) + +class SfaPermissionDenied(SfaFault): + def __init__(self, extra = None): + faultString = "Permission denied" + SfaFault.__init__(self, GENICODE.FORBIDDEN, faultString, extra) + +class SfaNotImplemented(SfaFault): + def __init__(self, interface=None, extra = None): + faultString = "Not implemented" + if interface: + faultString += " at interface " + interface + SfaFault.__init__(self, GENICODE.UNSUPPORTED, faultString, extra) + +class SfaAPIError(SfaFault): + def __init__(self, extra = None): + faultString = "Internal API error" + SfaFault.__init__(self, GENICODE.SERVERERROR, faultString, extra) + +class MalformedHrnException(SfaFault): + def __init__(self, value, extra = None): + self.value = value + faultString = "Malformed HRN: %(value)s" % locals() + SfaFault.__init__(self, GENICODE.ERROR, extra) + def __str__(self): + return repr(self.value) + +class TreeException(SfaFault): + def __init__(self, value, extra = None): + self.value = value + faultString = "Tree Exception: %(value)s, " % locals() + SfaFault.__init__(self, GENICODE.ERROR, faultString, extra) + def __str__(self): + return repr(self.value) + +class NonExistingRecord(SfaFault): + def __init__(self, value, extra = None): + self.value = value + faultString = "Non exsiting record %(value)s, " % locals() + SfaFault.__init__(self, GENICODE.SEARCHFAILED, faultString, extra) + def __str__(self): + return repr(self.value) + +class ExistingRecord(SfaFault): + def __init__(self, value, extra = None): + self.value = value + faultString = "Existing record: %(value)s, " % locals() + SfaFault.__init__(self, GENICODE.REFUSED, faultString, extra) + def __str__(self): + return repr(self.value) + + +class InvalidRPCParams(SfaFault): + def __init__(self, value, extra = None): + self.value = value + faultString = "Invalid RPC Params: %(value)s, " % locals() + SfaFault.__init__(self, GENICODE.RPCERROR, faultString, extra) + def __str__(self): + return repr(self.value) + +# SMBAKER exceptions follow + +class ConnectionKeyGIDMismatch(SfaFault): + def __init__(self, value, extra = None): + self.value = value + faultString = "Connection Key GID mismatch: %(value)s" % locals() + SfaFault.__init__(self, GENICODE.ERROR, faultString, extra) + def __str__(self): + return repr(self.value) + +class MissingCallerGID(SfaFault): + def __init__(self, value, extra = None): + self.value = value + faultString = "Missing Caller GID: %(value)s" % locals() + SfaFault.__init__(self, GENICODE.ERROR, faultString, extra) + def __str__(self): + return repr(self.value) + +class RecordNotFound(SfaFault): + def __init__(self, value, extra = None): + self.value = value + faultString = "Record not found: %(value)s" % locals() + SfaFault.__init__(self, GENICODE.ERROR, faultString, extra) + def __str__(self): + return repr(self.value) + +class UnknownSfaType(SfaFault): + def __init__(self, value, extra = None): + self.value = value + faultString = "Unknown SFA Type: %(value)s" % locals() + SfaFault.__init__(self, GENICODE.ERROR, faultString, extra) + def __str__(self): + return repr(self.value) + +class MissingAuthority(SfaFault): + def __init__(self, value, extra = None): + self.value = value + faultString = "Missing authority: %(value)s" % locals() + SfaFault.__init__(self, GENICODE.ERROR, faultString, extra) + def __str__(self): + return repr(self.value) + +class PlanetLabRecordDoesNotExist(SfaFault): + def __init__(self, value, extra = None): + self.value = value + faultString = "PlanetLab record does not exist : %(value)s" % locals() + SfaFault.__init__(self, GENICODE.ERROR, faultString, extra) + def __str__(self): + return repr(self.value) + +class PermissionError(SfaFault): + def __init__(self, value, extra = None): + self.value = value + faultString = "Permission error: %(value)s" % locals() + SfaFault.__init__(self, GENICODE.FORBIDDEN, faultString, extra) + def __str__(self): + return repr(self.value) + +class InsufficientRights(SfaFault): + def __init__(self, value, extra = None): + self.value = value + faultString = "Insufficient rights: %(value)s" % locals() + SfaFault.__init__(self, GENICODE.FORBIDDEN, faultString, extra) + def __str__(self): + return repr(self.value) + +class MissingDelegateBit(SfaFault): + def __init__(self, value, extra = None): + self.value = value + faultString = "Missing delegate bit: %(value)s" % locals() + SfaFault.__init__(self, GENICODE.FORBIDDEN, faultString, extra) + def __str__(self): + return repr(self.value) + +class ChildRightsNotSubsetOfParent(SfaFault): + def __init__(self, value, extra = None): + self.value = value + faultString = "Child rights not subset of parent: %(value)s" % locals() + SfaFault.__init__(self, GENICODE.FORBIDDEN, faultString, extra) + def __str__(self): + return repr(self.value) + +class CertMissingParent(SfaFault): + def __init__(self, value, extra = None): + self.value = value + faultString = "Cert missing parent: %(value)s" % locals() + SfaFault.__init__(self, GENICODE.ERROR, faultString, extra) + def __str__(self): + return repr(self.value) + +class CertNotSignedByParent(SfaFault): + def __init__(self, value, extra = None): + self.value = value + faultString = "Cert not signed by parent: %(value)s" % locals() + SfaFault.__init__(self, GENICODE.ERROR, faultString, extra) + def __str__(self): + return repr(self.value) + +class GidParentHrn(SfaFault): + def __init__(self, value, extra = None): + self.value = value + faultString = "Cert URN is not an extension of its parent: %(value)s" % locals() + SfaFault.__init__(self, GENICODE.ERROR, faultString, extra) + def __str__(self): + return repr(self.value) + +class GidInvalidParentHrn(SfaFault): + def __init__(self, value, extra = None): + self.value = value + faultString = "GID invalid parent hrn: %(value)s" % locals() + SfaFault.__init__(self, GENICODE.ERROR, faultString, extra) + def __str__(self): + return repr(self.value) + +class SliverDoesNotExist(SfaFault): + def __init__(self, value, extra = None): + self.value = value + faultString = "Sliver does not exist : %(value)s" % locals() + SfaFault.__init__(self, GENICODE.ERROR, faultString, extra) + def __str__(self): + return repr(self.value) + +class BadRequestHash(xmlrpclib.Fault): + def __init__(self, hash = None, extra = None): + faultString = "bad request hash: " + str(hash) + xmlrpclib.Fault.__init__(self, GENICODE.ERROR, faultString) + +class MissingTrustedRoots(SfaFault): + def __init__(self, value, extra = None): + self.value = value + faultString = "Trusted root directory does not exist: %(value)s" % locals() + SfaFault.__init__(self, GENICODE.SERVERERROR, faultString, extra) + def __str__(self): + return repr(self.value) + +class MissingSfaInfo(SfaFault): + def __init__(self, value, extra = None): + self.value = value + faultString = "Missing information: %(value)s" % locals() + SfaFault.__init__(self, GENICODE.ERROR, faultString, extra) + def __str__(self): + return repr(self.value) + +class InvalidRSpec(SfaFault): + def __init__(self, value, extra = None): + self.value = value + faultString = "Invalid RSpec: %(value)s" % locals() + SfaFault.__init__(self, GENICODE.ERROR, faultString, extra) + def __str__(self): + return repr(self.value) + +class InvalidRSpecVersion(SfaFault): + def __init__(self, value, extra = None): + self.value = value + faultString = "Invalid RSpec version: %(value)s" % locals() + SfaFault.__init__(self, GENICODE.BADVERSION, faultString, extra) + def __str__(self): + return repr(self.value) + +class UnsupportedRSpecVersion(SfaFault): + def __init__(self, value, extra = None): + self.value = value + faultString = "Unsupported RSpec version: %(value)s" % locals() + SfaFault.__init__(self, GENICODE.UNSUPPORTED, faultString, extra) + def __str__(self): + return repr(self.value) + +class InvalidRSpecElement(SfaFault): + def __init__(self, value, extra = None): + self.value = value + faultString = "Invalid RSpec Element: %(value)s" % locals() + SfaFault.__init__(self, GENICODE.ERROR, faultString, extra) + def __str__(self): + return repr(self.value) + +class InvalidXML(SfaFault): + def __init__(self, value, extra = None): + self.value = value + faultString = "Invalid XML Document: %(value)s" % locals() + SfaFault.__init__(self, GENICODE.ERROR, faultString, extra) + def __str__(self): + return repr(self.value) + +class AccountNotEnabled(SfaFault): + def __init__(self, extra = None): + faultString = "Account Disabled" + SfaFault.__init__(self, GENICODE.ERROR, faultString, extra) + def __str__(self): + return repr(self.value) + +class CredentialNotVerifiable(SfaFault): + def __init__(self, value, extra = None): + self.value = value + faultString = "Unable to verify credential: %(value)s, " %locals() + SfaFault.__init__(self, GENICODE.ERROR, faultString, extra) + def __str__(self): + return repr(self.value) + +class CertExpired(SfaFault): + def __init__(self, value, extra=None): + self.value = value + faultString = "%s cert is expired" % value + SfaFault.__init__(self, GENICODE.ERROR, faultString, extra) + diff --git a/sfa/util/genicode.py b/sfa/util/genicode.py index 61ae4895..ca201a0a 100644 --- a/sfa/util/genicode.py +++ b/sfa/util/genicode.py @@ -1,45 +1,45 @@ -#---------------------------------------------------------------------- -# Copyright (c) 2008 Board of Trustees, Princeton University -# -# Permission is hereby granted, free of charge, to any person obtaining -# a copy of this software and/or hardware specification (the "Work") to -# deal in the Work without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, -# and/or sell copies of the Work, and to permit persons to whom the Work -# is furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be -# included in all copies or substantial portions of the Work. -# -# THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS -# IN THE WORK. -#---------------------------------------------------------------------- - -from sfa.util.enumeration import Enum - -GENICODE = Enum( - SUCCESS=0, - BADARGS=1, - ERROR=2, - FORBIDDEN=3, - BADVERSION=4, - SERVERERROR=5, - TOOBIG=6, - REFUSED=7, - TIMEDOUT=8, - DBERROR=9, - RPCERROR=10, - UNAVAILABLE=11, - SEARCHFAILED=12, - UNSUPPORTED=13, - BUSY=14, - EXPIRED=15, - INPORGRESS=16, - ALREADYEXISTS=17 -) +#---------------------------------------------------------------------- +# Copyright (c) 2008 Board of Trustees, Princeton University +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and/or hardware specification (the "Work") to +# deal in the Work without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, +# and/or sell copies of the Work, and to permit persons to whom the Work +# is furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Work. +# +# THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS +# IN THE WORK. +#---------------------------------------------------------------------- + +from sfa.util.enumeration import Enum + +GENICODE = Enum( + SUCCESS=0, + BADARGS=1, + ERROR=2, + FORBIDDEN=3, + BADVERSION=4, + SERVERERROR=5, + TOOBIG=6, + REFUSED=7, + TIMEDOUT=8, + DBERROR=9, + RPCERROR=10, + UNAVAILABLE=11, + SEARCHFAILED=12, + UNSUPPORTED=13, + BUSY=14, + EXPIRED=15, + INPORGRESS=16, + ALREADYEXISTS=17 +) diff --git a/sfa/util/sfalogging.py b/sfa/util/sfalogging.py index 5529fe73..495a2747 100644 --- a/sfa/util/sfalogging.py +++ b/sfa/util/sfalogging.py @@ -1,201 +1,201 @@ -#!/usr/bin/python - -#---------------------------------------------------------------------- -# Copyright (c) 2008 Board of Trustees, Princeton University -# -# Permission is hereby granted, free of charge, to any person obtaining -# a copy of this software and/or hardware specification (the "Work") to -# deal in the Work without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, -# and/or sell copies of the Work, and to permit persons to whom the Work -# is furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be -# included in all copies or substantial portions of the Work. -# -# THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS -# IN THE WORK. -#---------------------------------------------------------------------- - -import os, sys -import traceback -import logging, logging.handlers - -CRITICAL=logging.CRITICAL -ERROR=logging.ERROR -WARNING=logging.WARNING -INFO=logging.INFO -DEBUG=logging.DEBUG - -# a logger that can handle tracebacks -class _SfaLogger: - def __init__ (self,logfile=None,loggername=None,level=logging.INFO): - # default is to locate loggername from the logfile if avail. - if not logfile: - #loggername='console' - #handler=logging.StreamHandler() - #handler.setFormatter(logging.Formatter("%(levelname)s %(message)s")) - logfile = "/var/log/sfa.log" - - if not loggername: - loggername=os.path.basename(logfile) - try: - handler=logging.handlers.RotatingFileHandler(logfile,maxBytes=1000000, backupCount=5) - except IOError: - # This is usually a permissions error becaue the file is - # owned by root, but httpd is trying to access it. - tmplogfile=os.getenv("TMPDIR", "/tmp") + os.path.sep + os.path.basename(logfile) - # In strange uses, 2 users on same machine might use same code, - # meaning they would clobber each others files - # We could (a) rename the tmplogfile, or (b) - # just log to the console in that case. - # Here we default to the console. - if os.path.exists(tmplogfile) and not os.access(tmplogfile,os.W_OK): - loggername = loggername + "-console" - handler = logging.StreamHandler() - else: - handler=logging.handlers.RotatingFileHandler(tmplogfile,maxBytes=1000000, backupCount=5) - handler.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")) - self.logger=logging.getLogger(loggername) - self.logger.setLevel(level) - # check if logger already has the handler we're about to add - handler_exists = False - for l_handler in self.logger.handlers: - if l_handler.baseFilename == handler.baseFilename and \ - l_handler.level == handler.level: - handler_exists = True - - if not handler_exists: - self.logger.addHandler(handler) - - self.loggername=loggername - - def setLevel(self,level): - self.logger.setLevel(level) - - # shorthand to avoid having to import logging all over the place - def setLevelDebug(self): - self.logger.setLevel(logging.DEBUG) - - # define a verbose option with s/t like - # parser.add_option("-v", "--verbose", action="count", dest="verbose", default=0) - # and pass the coresponding options.verbose to this method to adjust level - def setLevelFromOptVerbose(self,verbose): - if verbose==0: - self.logger.setLevel(logging.WARNING) - elif verbose==1: - self.logger.setLevel(logging.INFO) - elif verbose>=2: - self.logger.setLevel(logging.DEBUG) - # in case some other code needs a boolean - def getBoolVerboseFromOpt(self,verbose): - return verbose>=1 - - #################### - def info(self, msg): - self.logger.info(msg) - - def debug(self, msg): - self.logger.debug(msg) - - def warn(self, msg): - self.logger.warn(msg) - - # some code is using logger.warn(), some is using logger.warning() - def warning(self, msg): - self.logger.warning(msg) - - def error(self, msg): - self.logger.error(msg) - - def critical(self, msg): - self.logger.critical(msg) - - # logs an exception - use in an except statement - def log_exc(self,message): - self.error("%s BEG TRACEBACK"%message+"\n"+traceback.format_exc().strip("\n")) - self.error("%s END TRACEBACK"%message) - - def log_exc_critical(self,message): - self.critical("%s BEG TRACEBACK"%message+"\n"+traceback.format_exc().strip("\n")) - self.critical("%s END TRACEBACK"%message) - - # for investigation purposes, can be placed anywhere - def log_stack(self,message): - to_log="".join(traceback.format_stack()) - self.info("%s BEG STACK"%message+"\n"+to_log) - self.info("%s END STACK"%message) - - def enable_console(self, stream=sys.stdout): - formatter = logging.Formatter("%(message)s") - handler = logging.StreamHandler(stream) - handler.setFormatter(formatter) - self.logger.addHandler(handler) - - -info_logger = _SfaLogger(loggername='info', level=logging.INFO) -debug_logger = _SfaLogger(loggername='debug', level=logging.DEBUG) -warn_logger = _SfaLogger(loggername='warning', level=logging.WARNING) -error_logger = _SfaLogger(loggername='error', level=logging.ERROR) -critical_logger = _SfaLogger(loggername='critical', level=logging.CRITICAL) -logger = info_logger -sfi_logger = _SfaLogger(logfile=os.path.expanduser("~/.sfi/")+'sfi.log',loggername='sfilog', level=logging.DEBUG) -######################################## -import time - -def profile(logger): - """ - Prints the runtime of the specified callable. Use as a decorator, e.g., - - @profile(logger) - def foo(...): - ... - """ - def logger_profile(callable): - def wrapper(*args, **kwds): - 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.iteritems()] - # should probably use debug, but then debug is not always enabled - logger.info("PROFILED %s (%s): %.02f s" % (callable.__name__, ", ".join(args), end - start)) - return result - return wrapper - return logger_profile - - -if __name__ == '__main__': - print 'testing sfalogging into logger.log' - logger1=_SfaLogger('logger.log', loggername='std(info)') - logger2=_SfaLogger('logger.log', loggername='error', level=logging.ERROR) - logger3=_SfaLogger('logger.log', loggername='debug', level=logging.DEBUG) - - for (logger,msg) in [ (logger1,"std(info)"),(logger2,"error"),(logger3,"debug")]: - - print "====================",msg, logger.logger.handlers - - logger.enable_console() - logger.critical("logger.critical") - logger.error("logger.error") - logger.warn("logger.warning") - logger.info("logger.info") - logger.debug("logger.debug") - logger.setLevel(logging.DEBUG) - logger.debug("logger.debug again") - - @profile(logger) - def sleep(seconds = 1): - time.sleep(seconds) - - logger.info('console.info') - sleep(0.5) - logger.setLevel(logging.DEBUG) - sleep(0.25) - +#!/usr/bin/python + +#---------------------------------------------------------------------- +# Copyright (c) 2008 Board of Trustees, Princeton University +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and/or hardware specification (the "Work") to +# deal in the Work without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, +# and/or sell copies of the Work, and to permit persons to whom the Work +# is furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Work. +# +# THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS +# IN THE WORK. +#---------------------------------------------------------------------- + +import os, sys +import traceback +import logging, logging.handlers + +CRITICAL=logging.CRITICAL +ERROR=logging.ERROR +WARNING=logging.WARNING +INFO=logging.INFO +DEBUG=logging.DEBUG + +# a logger that can handle tracebacks +class _SfaLogger: + def __init__ (self,logfile=None,loggername=None,level=logging.INFO): + # default is to locate loggername from the logfile if avail. + if not logfile: + #loggername='console' + #handler=logging.StreamHandler() + #handler.setFormatter(logging.Formatter("%(levelname)s %(message)s")) + logfile = "/var/log/sfa.log" + + if not loggername: + loggername=os.path.basename(logfile) + try: + handler=logging.handlers.RotatingFileHandler(logfile,maxBytes=1000000, backupCount=5) + except IOError: + # This is usually a permissions error becaue the file is + # owned by root, but httpd is trying to access it. + tmplogfile=os.getenv("TMPDIR", "/tmp") + os.path.sep + os.path.basename(logfile) + # In strange uses, 2 users on same machine might use same code, + # meaning they would clobber each others files + # We could (a) rename the tmplogfile, or (b) + # just log to the console in that case. + # Here we default to the console. + if os.path.exists(tmplogfile) and not os.access(tmplogfile,os.W_OK): + loggername = loggername + "-console" + handler = logging.StreamHandler() + else: + handler=logging.handlers.RotatingFileHandler(tmplogfile,maxBytes=1000000, backupCount=5) + handler.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")) + self.logger=logging.getLogger(loggername) + self.logger.setLevel(level) + # check if logger already has the handler we're about to add + handler_exists = False + for l_handler in self.logger.handlers: + if l_handler.baseFilename == handler.baseFilename and \ + l_handler.level == handler.level: + handler_exists = True + + if not handler_exists: + self.logger.addHandler(handler) + + self.loggername=loggername + + def setLevel(self,level): + self.logger.setLevel(level) + + # shorthand to avoid having to import logging all over the place + def setLevelDebug(self): + self.logger.setLevel(logging.DEBUG) + + # define a verbose option with s/t like + # parser.add_option("-v", "--verbose", action="count", dest="verbose", default=0) + # and pass the coresponding options.verbose to this method to adjust level + def setLevelFromOptVerbose(self,verbose): + if verbose==0: + self.logger.setLevel(logging.WARNING) + elif verbose==1: + self.logger.setLevel(logging.INFO) + elif verbose>=2: + self.logger.setLevel(logging.DEBUG) + # in case some other code needs a boolean + def getBoolVerboseFromOpt(self,verbose): + return verbose>=1 + + #################### + def info(self, msg): + self.logger.info(msg) + + def debug(self, msg): + self.logger.debug(msg) + + def warn(self, msg): + self.logger.warn(msg) + + # some code is using logger.warn(), some is using logger.warning() + def warning(self, msg): + self.logger.warning(msg) + + def error(self, msg): + self.logger.error(msg) + + def critical(self, msg): + self.logger.critical(msg) + + # logs an exception - use in an except statement + def log_exc(self,message): + self.error("%s BEG TRACEBACK"%message+"\n"+traceback.format_exc().strip("\n")) + self.error("%s END TRACEBACK"%message) + + def log_exc_critical(self,message): + self.critical("%s BEG TRACEBACK"%message+"\n"+traceback.format_exc().strip("\n")) + self.critical("%s END TRACEBACK"%message) + + # for investigation purposes, can be placed anywhere + def log_stack(self,message): + to_log="".join(traceback.format_stack()) + self.info("%s BEG STACK"%message+"\n"+to_log) + self.info("%s END STACK"%message) + + def enable_console(self, stream=sys.stdout): + formatter = logging.Formatter("%(message)s") + handler = logging.StreamHandler(stream) + handler.setFormatter(formatter) + self.logger.addHandler(handler) + + +info_logger = _SfaLogger(loggername='info', level=logging.INFO) +debug_logger = _SfaLogger(loggername='debug', level=logging.DEBUG) +warn_logger = _SfaLogger(loggername='warning', level=logging.WARNING) +error_logger = _SfaLogger(loggername='error', level=logging.ERROR) +critical_logger = _SfaLogger(loggername='critical', level=logging.CRITICAL) +logger = info_logger +sfi_logger = _SfaLogger(logfile=os.path.expanduser("~/.sfi/")+'sfi.log',loggername='sfilog', level=logging.DEBUG) +######################################## +import time + +def profile(logger): + """ + Prints the runtime of the specified callable. Use as a decorator, e.g., + + @profile(logger) + def foo(...): + ... + """ + def logger_profile(callable): + def wrapper(*args, **kwds): + 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.iteritems()] + # should probably use debug, but then debug is not always enabled + logger.info("PROFILED %s (%s): %.02f s" % (callable.__name__, ", ".join(args), end - start)) + return result + return wrapper + return logger_profile + + +if __name__ == '__main__': + print 'testing sfalogging into logger.log' + logger1=_SfaLogger('logger.log', loggername='std(info)') + logger2=_SfaLogger('logger.log', loggername='error', level=logging.ERROR) + logger3=_SfaLogger('logger.log', loggername='debug', level=logging.DEBUG) + + for (logger,msg) in [ (logger1,"std(info)"),(logger2,"error"),(logger3,"debug")]: + + print "====================",msg, logger.logger.handlers + + logger.enable_console() + logger.critical("logger.critical") + logger.error("logger.error") + logger.warn("logger.warning") + logger.info("logger.info") + logger.debug("logger.debug") + logger.setLevel(logging.DEBUG) + logger.debug("logger.debug again") + + @profile(logger) + def sleep(seconds = 1): + time.sleep(seconds) + + logger.info('console.info') + sleep(0.5) + logger.setLevel(logging.DEBUG) + sleep(0.25) + diff --git a/sfa/util/sfatime.py b/sfa/util/sfatime.py index 70f88302..48796892 100644 --- a/sfa/util/sfatime.py +++ b/sfa/util/sfatime.py @@ -1,66 +1,66 @@ -#---------------------------------------------------------------------- -# Copyright (c) 2008 Board of Trustees, Princeton University -# -# Permission is hereby granted, free of charge, to any person obtaining -# a copy of this software and/or hardware specification (the "Work") to -# deal in the Work without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, -# and/or sell copies of the Work, and to permit persons to whom the Work -# is furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be -# included in all copies or substantial portions of the Work. -# -# THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS -# IN THE WORK. -#---------------------------------------------------------------------- -from types import StringTypes -import dateutil.parser -import datetime -import time - -from sfa.util.sfalogging import logger - -DATEFORMAT = "%Y-%m-%dT%H:%M:%SZ" - -def utcparse(input): - """ Translate a string into a time using dateutil.parser.parse but make sure it's in UTC time and strip -the timezone, so that it's compatible with normal datetime.datetime objects. - -For safety this can also handle inputs that are either timestamps, or datetimes -""" - # prepare the input for the checks below by - # casting strings ('1327098335') to ints - if isinstance(input, StringTypes): - try: - input = int(input) - except ValueError: - pass - - if isinstance (input, datetime.datetime): - logger.warn ("argument to utcparse already a datetime - doing nothing") - return input - elif isinstance (input, StringTypes): - t = dateutil.parser.parse(input) - if t.utcoffset() is not None: - t = t.utcoffset() + t.replace(tzinfo=None) - return t - elif isinstance (input, (int,float,long)): - return datetime.datetime.fromtimestamp(input) - else: - logger.error("Unexpected type in utcparse [%s]"%type(input)) - -def datetime_to_string(input): - return datetime.datetime.strftime(input, DATEFORMAT) - -def datetime_to_utc(input): - return time.gmtime(datetime_to_epoch(input)) - -def datetime_to_epoch(input): - return int(time.mktime(input.timetuple())) +#---------------------------------------------------------------------- +# Copyright (c) 2008 Board of Trustees, Princeton University +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and/or hardware specification (the "Work") to +# deal in the Work without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, +# and/or sell copies of the Work, and to permit persons to whom the Work +# is furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Work. +# +# THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS +# IN THE WORK. +#---------------------------------------------------------------------- +from types import StringTypes +import dateutil.parser +import datetime +import time + +from sfa.util.sfalogging import logger + +DATEFORMAT = "%Y-%m-%dT%H:%M:%SZ" + +def utcparse(input): + """ Translate a string into a time using dateutil.parser.parse but make sure it's in UTC time and strip +the timezone, so that it's compatible with normal datetime.datetime objects. + +For safety this can also handle inputs that are either timestamps, or datetimes +""" + # prepare the input for the checks below by + # casting strings ('1327098335') to ints + if isinstance(input, StringTypes): + try: + input = int(input) + except ValueError: + pass + + if isinstance (input, datetime.datetime): + logger.warn ("argument to utcparse already a datetime - doing nothing") + return input + elif isinstance (input, StringTypes): + t = dateutil.parser.parse(input) + if t.utcoffset() is not None: + t = t.utcoffset() + t.replace(tzinfo=None) + return t + elif isinstance (input, (int,float,long)): + return datetime.datetime.fromtimestamp(input) + else: + logger.error("Unexpected type in utcparse [%s]"%type(input)) + +def datetime_to_string(input): + return datetime.datetime.strftime(input, DATEFORMAT) + +def datetime_to_utc(input): + return time.gmtime(datetime_to_epoch(input)) + +def datetime_to_epoch(input): + return int(time.mktime(input.timetuple())) diff --git a/sfa/util/xrn.py b/sfa/util/xrn.py index 02f4adb9..e548fa56 100644 --- a/sfa/util/xrn.py +++ b/sfa/util/xrn.py @@ -1,268 +1,268 @@ -#---------------------------------------------------------------------- -# Copyright (c) 2008 Board of Trustees, Princeton University -# -# Permission is hereby granted, free of charge, to any person obtaining -# a copy of this software and/or hardware specification (the "Work") to -# deal in the Work without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, -# and/or sell copies of the Work, and to permit persons to whom the Work -# is furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be -# included in all copies or substantial portions of the Work. -# -# THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS -# IN THE WORK. -#---------------------------------------------------------------------- - -import re - -from sfa.util.faults import SfaAPIError - -# for convenience and smoother translation - we should get rid of these functions eventually -def get_leaf(hrn): return Xrn(hrn).get_leaf() -def get_authority(hrn): return Xrn(hrn).get_authority_hrn() -def urn_to_hrn(urn): xrn=Xrn(urn); return (xrn.hrn, xrn.type) -def hrn_to_urn(hrn,type): return Xrn(hrn, type=type).urn -def hrn_authfor_hrn(parenthrn, hrn): return Xrn.hrn_is_auth_for_hrn(parenthrn, hrn) - -class Xrn: - - ########## basic tools on HRNs - # split a HRN-like string into pieces - # this is like split('.') except for escaped (backslashed) dots - # e.g. hrn_split ('a\.b.c.d') -> [ 'a\.b','c','d'] - @staticmethod - def hrn_split(hrn): - return [ x.replace('--sep--','\\.') for x in hrn.replace('\\.','--sep--').split('.') ] - - # e.g. hrn_leaf ('a\.b.c.d') -> 'd' - @staticmethod - def hrn_leaf(hrn): return Xrn.hrn_split(hrn)[-1] - - # e.g. hrn_auth_list ('a\.b.c.d') -> ['a\.b', 'c'] - @staticmethod - def hrn_auth_list(hrn): return Xrn.hrn_split(hrn)[0:-1] - - # e.g. hrn_auth ('a\.b.c.d') -> 'a\.b.c' - @staticmethod - def hrn_auth(hrn): return '.'.join(Xrn.hrn_auth_list(hrn)) - - # e.g. escape ('a.b') -> 'a\.b' - @staticmethod - def escape(token): return re.sub(r'([^\\])\.', r'\1\.', token) - - # e.g. unescape ('a\.b') -> 'a.b' - @staticmethod - def unescape(token): return token.replace('\\.','.') - - # Return the HRN authority chain from top to bottom. - # e.g. hrn_auth_chain('a\.b.c.d') -> ['a\.b', 'a\.b.c'] - @staticmethod - def hrn_auth_chain(hrn): - parts = Xrn.hrn_auth_list(hrn) - chain = [] - for i in range(len(parts)): - chain.append('.'.join(parts[:i+1])) - # Include the HRN itself? - #chain.append(hrn) - return chain - - # Is the given HRN a true authority over the namespace of the other - # child HRN? - # A better alternative than childHRN.startswith(parentHRN) - # e.g. hrn_is_auth_for_hrn('a\.b', 'a\.b.c.d') -> True, - # but hrn_is_auth_for_hrn('a', 'a\.b.c.d') -> False - # Also hrn_is_auth_for_hrn('a\.b.c.d', 'a\.b.c.d') -> True - @staticmethod - def hrn_is_auth_for_hrn(parenthrn, hrn): - if parenthrn == hrn: - return True - for auth in Xrn.hrn_auth_chain(hrn): - if parenthrn == auth: - return True - return False - - ########## basic tools on URNs - URN_PREFIX = "urn:publicid:IDN" - URN_PREFIX_lower = "urn:publicid:idn" - - @staticmethod - def is_urn (text): - return text.lower().startswith(Xrn.URN_PREFIX_lower) - - @staticmethod - def urn_full (urn): - if Xrn.is_urn(urn): return urn - else: return Xrn.URN_PREFIX+urn - @staticmethod - def urn_meaningful (urn): - if Xrn.is_urn(urn): return urn[len(Xrn.URN_PREFIX):] - else: return urn - @staticmethod - def urn_split (urn): - return Xrn.urn_meaningful(urn).split('+') - - #################### - # the local fields that are kept consistent - # self.urn - # self.hrn - # self.type - # self.path - # provide either urn, or (hrn + type) - def __init__ (self, xrn, type=None, id=None): - if not xrn: xrn = "" - # user has specified xrn : guess if urn or hrn - self.id = id - if Xrn.is_urn(xrn): - self.hrn=None - self.urn=xrn - if id: - self.urn = "%s:%s" % (self.urn, str(id)) - self.urn_to_hrn() - else: - self.urn=None - self.hrn=xrn - self.type=type - self.hrn_to_urn() - self._normalize() -# happens all the time .. -# if not type: -# debug_logger.debug("type-less Xrn's are not safe") - - def __repr__ (self): - result=" 1: - self.id = ":".join(parts[1:]) - name = parts[0] - hrn += '.%s' % Xrn.escape(name) - - self.hrn=str(hrn) - self.type=str(type) - - def hrn_to_urn(self): - """ - compute urn from (hrn, type) - """ - -# if not self.hrn or self.hrn.startswith(Xrn.URN_PREFIX): - if Xrn.is_urn(self.hrn): - raise SfaAPIError, "Xrn.hrn_to_urn, hrn=%s"%self.hrn - - if self.type and self.type.startswith('authority'): - self.authority = Xrn.hrn_auth_list(self.hrn) - leaf = self.get_leaf() - #if not self.authority: - # self.authority = [self.hrn] - type_parts = self.type.split("+") - self.type = type_parts[0] - name = 'sa' - if len(type_parts) > 1: - name = type_parts[1] - auth_parts = [part for part in [self.get_authority_urn(), leaf] if part] - authority_string = ":".join(auth_parts) - else: - self.authority = Xrn.hrn_auth_list(self.hrn) - name = Xrn.hrn_leaf(self.hrn) - authority_string = self.get_authority_urn() - - if self.type == None: - urn = "+".join(['',authority_string,Xrn.unescape(name)]) - else: - urn = "+".join(['',authority_string,self.type,Xrn.unescape(name)]) - - if hasattr(self, 'id') and self.id: - urn = "%s:%s" % (urn, self.id) - - self.urn = Xrn.URN_PREFIX + urn - - def dump_string(self): - result="-------------------- XRN\n" - result += "URN=%s\n"%self.urn - result += "HRN=%s\n"%self.hrn - result += "TYPE=%s\n"%self.type - result += "LEAF=%s\n"%self.get_leaf() - result += "AUTH(hrn format)=%s\n"%self.get_authority_hrn() - result += "AUTH(urn format)=%s\n"%self.get_authority_urn() - return result - +#---------------------------------------------------------------------- +# Copyright (c) 2008 Board of Trustees, Princeton University +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and/or hardware specification (the "Work") to +# deal in the Work without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, +# and/or sell copies of the Work, and to permit persons to whom the Work +# is furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Work. +# +# THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS +# IN THE WORK. +#---------------------------------------------------------------------- + +import re + +from sfa.util.faults import SfaAPIError + +# for convenience and smoother translation - we should get rid of these functions eventually +def get_leaf(hrn): return Xrn(hrn).get_leaf() +def get_authority(hrn): return Xrn(hrn).get_authority_hrn() +def urn_to_hrn(urn): xrn=Xrn(urn); return (xrn.hrn, xrn.type) +def hrn_to_urn(hrn,type): return Xrn(hrn, type=type).urn +def hrn_authfor_hrn(parenthrn, hrn): return Xrn.hrn_is_auth_for_hrn(parenthrn, hrn) + +class Xrn: + + ########## basic tools on HRNs + # split a HRN-like string into pieces + # this is like split('.') except for escaped (backslashed) dots + # e.g. hrn_split ('a\.b.c.d') -> [ 'a\.b','c','d'] + @staticmethod + def hrn_split(hrn): + return [ x.replace('--sep--','\\.') for x in hrn.replace('\\.','--sep--').split('.') ] + + # e.g. hrn_leaf ('a\.b.c.d') -> 'd' + @staticmethod + def hrn_leaf(hrn): return Xrn.hrn_split(hrn)[-1] + + # e.g. hrn_auth_list ('a\.b.c.d') -> ['a\.b', 'c'] + @staticmethod + def hrn_auth_list(hrn): return Xrn.hrn_split(hrn)[0:-1] + + # e.g. hrn_auth ('a\.b.c.d') -> 'a\.b.c' + @staticmethod + def hrn_auth(hrn): return '.'.join(Xrn.hrn_auth_list(hrn)) + + # e.g. escape ('a.b') -> 'a\.b' + @staticmethod + def escape(token): return re.sub(r'([^\\])\.', r'\1\.', token) + + # e.g. unescape ('a\.b') -> 'a.b' + @staticmethod + def unescape(token): return token.replace('\\.','.') + + # Return the HRN authority chain from top to bottom. + # e.g. hrn_auth_chain('a\.b.c.d') -> ['a\.b', 'a\.b.c'] + @staticmethod + def hrn_auth_chain(hrn): + parts = Xrn.hrn_auth_list(hrn) + chain = [] + for i in range(len(parts)): + chain.append('.'.join(parts[:i+1])) + # Include the HRN itself? + #chain.append(hrn) + return chain + + # Is the given HRN a true authority over the namespace of the other + # child HRN? + # A better alternative than childHRN.startswith(parentHRN) + # e.g. hrn_is_auth_for_hrn('a\.b', 'a\.b.c.d') -> True, + # but hrn_is_auth_for_hrn('a', 'a\.b.c.d') -> False + # Also hrn_is_auth_for_hrn('a\.b.c.d', 'a\.b.c.d') -> True + @staticmethod + def hrn_is_auth_for_hrn(parenthrn, hrn): + if parenthrn == hrn: + return True + for auth in Xrn.hrn_auth_chain(hrn): + if parenthrn == auth: + return True + return False + + ########## basic tools on URNs + URN_PREFIX = "urn:publicid:IDN" + URN_PREFIX_lower = "urn:publicid:idn" + + @staticmethod + def is_urn (text): + return text.lower().startswith(Xrn.URN_PREFIX_lower) + + @staticmethod + def urn_full (urn): + if Xrn.is_urn(urn): return urn + else: return Xrn.URN_PREFIX+urn + @staticmethod + def urn_meaningful (urn): + if Xrn.is_urn(urn): return urn[len(Xrn.URN_PREFIX):] + else: return urn + @staticmethod + def urn_split (urn): + return Xrn.urn_meaningful(urn).split('+') + + #################### + # the local fields that are kept consistent + # self.urn + # self.hrn + # self.type + # self.path + # provide either urn, or (hrn + type) + def __init__ (self, xrn, type=None, id=None): + if not xrn: xrn = "" + # user has specified xrn : guess if urn or hrn + self.id = id + if Xrn.is_urn(xrn): + self.hrn=None + self.urn=xrn + if id: + self.urn = "%s:%s" % (self.urn, str(id)) + self.urn_to_hrn() + else: + self.urn=None + self.hrn=xrn + self.type=type + self.hrn_to_urn() + self._normalize() +# happens all the time .. +# if not type: +# debug_logger.debug("type-less Xrn's are not safe") + + def __repr__ (self): + result=" 1: + self.id = ":".join(parts[1:]) + name = parts[0] + hrn += '.%s' % Xrn.escape(name) + + self.hrn=str(hrn) + self.type=str(type) + + def hrn_to_urn(self): + """ + compute urn from (hrn, type) + """ + +# if not self.hrn or self.hrn.startswith(Xrn.URN_PREFIX): + if Xrn.is_urn(self.hrn): + raise SfaAPIError, "Xrn.hrn_to_urn, hrn=%s"%self.hrn + + if self.type and self.type.startswith('authority'): + self.authority = Xrn.hrn_auth_list(self.hrn) + leaf = self.get_leaf() + #if not self.authority: + # self.authority = [self.hrn] + type_parts = self.type.split("+") + self.type = type_parts[0] + name = 'sa' + if len(type_parts) > 1: + name = type_parts[1] + auth_parts = [part for part in [self.get_authority_urn(), leaf] if part] + authority_string = ":".join(auth_parts) + else: + self.authority = Xrn.hrn_auth_list(self.hrn) + name = Xrn.hrn_leaf(self.hrn) + authority_string = self.get_authority_urn() + + if self.type == None: + urn = "+".join(['',authority_string,Xrn.unescape(name)]) + else: + urn = "+".join(['',authority_string,self.type,Xrn.unescape(name)]) + + if hasattr(self, 'id') and self.id: + urn = "%s:%s" % (urn, self.id) + + self.urn = Xrn.URN_PREFIX + urn + + def dump_string(self): + result="-------------------- XRN\n" + result += "URN=%s\n"%self.urn + result += "HRN=%s\n"%self.hrn + result += "TYPE=%s\n"%self.type + result += "LEAF=%s\n"%self.get_leaf() + result += "AUTH(hrn format)=%s\n"%self.get_authority_hrn() + result += "AUTH(urn format)=%s\n"%self.get_authority_urn() + return result + -- 2.45.2