dos2unix
authorThierry Parmentelat <thierry.parmentelat@sophia.inria.fr>
Mon, 3 Sep 2012 12:31:25 +0000 (14:31 +0200)
committerThierry Parmentelat <thierry.parmentelat@sophia.inria.fr>
Mon, 3 Sep 2012 12:31:25 +0000 (14:31 +0200)
sfa/util/enumeration.py
sfa/util/faults.py
sfa/util/genicode.py
sfa/util/sfalogging.py
sfa/util/sfatime.py
sfa/util/xrn.py

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