resolve conflict manually
authorBarış Metin <Talip-Baris.Metin@sophia.inria.fr>
Wed, 13 Oct 2010 14:56:24 +0000 (16:56 +0200)
committerBarış Metin <Talip-Baris.Metin@sophia.inria.fr>
Wed, 13 Oct 2010 14:56:24 +0000 (16:56 +0200)
74 files changed:
config/sfa_component_config
sfa.spec
sfa/client/getRecord.py
sfa/client/setRecord.py
sfa/client/sfadump.py [changed mode: 0644->0755]
sfa/client/sfi.py
sfa/init.d/sfa
sfa/managers/aggregate_manager_eucalyptus.py
sfa/managers/aggregate_manager_max.py
sfa/managers/aggregate_manager_openflow.py
sfa/managers/aggregate_manager_pl.py
sfa/managers/aggregate_manager_vini.py
sfa/managers/component_manager_pl.py
sfa/managers/registry_manager_pl.py
sfa/managers/slice_manager_pl.py
sfa/methods/CreateSliver.py
sfa/methods/DeleteSliver.py
sfa/methods/GetCredential.py
sfa/methods/GetSelfCredential.py
sfa/methods/GetTicket.py
sfa/methods/GetVersion.py
sfa/methods/List.py
sfa/methods/ListResources.py
sfa/methods/ListSlices.py
sfa/methods/RegisterPeerObject.py
sfa/methods/Remove.py
sfa/methods/RenewSliver.py
sfa/methods/Resolve.py
sfa/methods/ResolveGENI.py
sfa/methods/Shutdown.py
sfa/methods/SliverStatus.py
sfa/methods/Start.py
sfa/methods/Stop.py
sfa/methods/UpdateSliver.py
sfa/methods/get_aggregates.py
sfa/methods/get_key.py
sfa/methods/get_registries.py
sfa/methods/register_peer_object.py
sfa/methods/reset_slice.py
sfa/plc/api.py
sfa/plc/network.py
sfa/plc/sfa-import-plc.py
sfa/plc/sfa-nuke-plc.py
sfa/plc/sfaImport.py
sfa/plc/slices.py
sfa/rspecs/aggregates/rspec_manager_max.py
sfa/rspecs/aggregates/rspec_manager_openflow.py
sfa/server/aggregate.py
sfa/server/interface.py
sfa/server/modpython/SfaAggregateModPython.py
sfa/server/modpython/SfaRegistryModPython.py
sfa/server/modpython/SfaSliceMgrModPython.py
sfa/server/modpythonapi/ModPython.py
sfa/server/registry.py
sfa/server/sfa-clean-peer-records.py
sfa/server/sfa-server.py
sfa/server/sfa_component_setup.py
sfa/server/slicemgr.py
sfa/trust/auth.py
sfa/trust/certificate.py
sfa/trust/credential.py
sfa/trust/credential_legacy.py
sfa/trust/gid.py
sfa/trust/hierarchy.py
sfa/util/PostgreSQL.py
sfa/util/api.py
sfa/util/componentserver.py
sfa/util/method.py
sfa/util/namespace.py
sfa/util/record.py
sfa/util/rspec.py
sfa/util/server.py
sfa/util/sfalogging.py
sfa/util/xmlrpcprotocol.py

index 137405e..d51c93b 100644 (file)
@@ -108,7 +108,6 @@ SFA_CM_PORT=12346
 
 
 # Directory internal data gets stored
-# using /etc/sfa until gec5 but /var/lib/sfa would be a more reasonable choice
 SFA_CONFIG_DIR="/etc/sfa"
 
 # Directory internal data gets stored
index ef13aeb..89a687f 100644 (file)
--- a/sfa.spec
+++ b/sfa.spec
@@ -6,7 +6,7 @@
 
 %define name sfa
 %define version 1.0
-%define taglevel 1
+%define taglevel 2
 
 %define release %{taglevel}%{?pldistro:.%{pldistro}}%{?date:.%{date}}
 %global python_sitearch        %( python -c "from distutils.sysconfig import get_python_lib; print get_python_lib(1)" )
@@ -175,6 +175,19 @@ fi
 
 
 %changelog
+* Mon Oct 11 2010 Thierry Parmentelat <thierry.parmentelat@sophia.inria.fr> - sfa-1.0-2
+- deprecated old methods (e.g. List/list, and GetCredential/get_credential)
+- NOTE:  get_(self_)credential both have type and hrn swapped when moving to Get(Self)Credential
+- hrn-urn translations tweaked
+- fixed 'service sfa status'
+- sfa-nuke-plc has a -f/--file-system option to clean up /var/lib/authorities (exp.)
+- started to repair sfadump - although not usable yet
+- trust objects now have dump_string method that dump() actually prints
+- unit tests under review
+- logging cleanup ongoing (always safe to use sfalogging.sfa_logger())
+- binaries now support -v or -vv to increase loglevel
+- trashed obsolete sfa.util.client
+
 * Mon Oct 04 2010 Thierry Parmentelat <thierry.parmentelat@sophia.inria.fr> - sfa-1.0-1
 - various bugfixes and cleanup, improved/harmonized logging
 
@@ -210,6 +223,19 @@ fi
   cache and use in more general ways.     
 
 %changelog
+* Mon Oct 11 2010 Thierry Parmentelat <thierry.parmentelat@sophia.inria.fr> - sfa-1.0-2
+- deprecated old methods (e.g. List/list, and GetCredential/get_credential)
+- NOTE:  get_(self_)credential both have type and hrn swapped when moving to Get(Self)Credential
+- hrn-urn translations tweaked
+- fixed 'service sfa status'
+- sfa-nuke-plc has a -f/--file-system option to clean up /var/lib/authorities (exp.)
+- started to repair sfadump - although not usable yet
+- trust objects now have dump_string method that dump() actually prints
+- unit tests under review
+- logging cleanup ongoing (always safe to use sfalogging.sfa_logger())
+- binaries now support -v or -vv to increase loglevel
+- trashed obsolete sfa.util.client
+
 * Mon Oct 04 2010 Thierry Parmentelat <thierry.parmentelat@sophia.inria.fr> - sfa-1.0-1
 - various bugfixes and cleanup, improved/harmonized logging
 
index 546e90a..cb765e0 100755 (executable)
@@ -7,8 +7,6 @@ Filters/Prints record objects
 faiyaza at cs dot princeton dot edu
 Copyright (c) 2009 Board of Trustees, Princeton University
 
-$Id$
-$HeadURL$
 """
 
 import sys
index fd7fa83..5f48e68 100755 (executable)
@@ -7,8 +7,6 @@ Updates record objects
 faiyaza at cs dot princeton dot edu
 Copyright (c) 2009 Board of Trustees, Princeton University
 
-$Id$
-$HeadURL$
 """
 
 import sys
old mode 100644 (file)
new mode 100755 (executable)
index 6496ca6..b1169b9
@@ -1,6 +1,4 @@
 #! /usr/bin/env python
-# $Id$
-# $URL$
 from __future__ import with_statement
 
 import sys
@@ -12,23 +10,38 @@ from optparse import OptionParser
 
 from sfa.trust.certificate import Certificate
 from sfa.trust.credential import Credential
+from sfa.trust.gid import GID
 from sfa.util.record import SfaRecord
 from sfa.util.rspec import RSpec
+from sfa.util.sfalogging import sfa_logger, sfa_logger_goes_to_console
 
 def determine_sfa_filekind(fn):
-    cert = Certificate(filename = fn)
 
-    data = cert.get_data()
-    if data:
-        dict = xmlrpclib.loads(data)[0][0]
-    else:
-        dict = {}
+    if fn.endswith('.gid'): return 'gid'
+    elif fn.endswith('.cert'): return 'certificate'
+    elif fn.endswith('cred'): return 'credential'
+
+    try:
+        cred=Credential(filename=fn)
+        return 'credential'
+    except: pass
 
-    if "gidCaller" in dict:
-        return "credential"
+    try: 
+        gid=GID(filename=fn)
+        if gid.uuid: return 'gid'
+    except: pass
 
-    if "uuid" in dict:
-        return "gid"
+    try:
+        cert = Certificate(filename = fn)
+        return 'certificate'
+    except: pass
+
+    # to be completed
+#    if "gidCaller" in dict:
+#        return "credential"
+#
+#    if "uuid" in dict:
+#        return "gid"
 
     return "unknown"
 
@@ -54,41 +67,56 @@ def extract_gids(cred, extract_parents):
    if gidObject and ((gidCaller == None) or (gidCaller.get_hrn() != gidObject.get_hrn())):
        save_gid(gidObject)
 
-   if extract_parents:
-       parent = cred.get_parent()
-       if parent:
-           extract_gids(parent, extract_parents)
-
-def create_parser():
-   # Generate command line parser
-   parser = OptionParser(usage="%prog [options] filename")
-
-   parser.add_option("-e", "--extractgids", action="store_true", dest="extract_gids", default=False, help="Extract GIDs from credentials")
-   parser.add_option("-p", "--dumpparents", action="store_true", dest="dump_parents", default=False, help="Show parents")
-
-   return parser
+   # no such method Credential.get_parent
+#   if extract_parents:
+#       parent = cred.get_parent()
+#       if parent:
+#           extract_gids(parent, extract_parents)
+
+def handle_input (filename, options):
+    kind = determine_sfa_filekind(filename)
+    handle_input_kind (filename,options,kind)
+
+def handle_input_kind (filename, options, kind):
+    
+
+# dump methods current do 'print' so let's go this road for now
+    if kind=="certificate":
+        cert=Certificate (filename=filename)
+        print '--------------------',filename,'IS A',kind
+        cert.dump(show_extensions=options.show_extensions)
+    elif kind=="credential":
+        cred = Credential(filename = filename)
+        print '--------------------',filename,'IS A',kind
+        cred.dump(dump_parents = options.dump_parents)
+        if options.extract_gids:
+            print '--------------------',filename,'embedded GIDS'
+            extract_gids(cred, extract_parents = options.dump_parents)
+    elif kind=="gid":
+        gid = GID(filename = filename)
+        print '--------------------',filename,'IS A',kind
+        gid.dump(dump_parents = options.dump_parents)
+    else:
+        print "%s: unknown filekind '%s'"% (filename,kind)
 
 def main():
-   parser = create_parser()
-   (options, args) = parser.parse_args()
-
-   if len(args) <= 0:
-        print "No filename given. Use -h for help."
-        return -1
-
-   filename = args[0]
-   kind = determine_sfa_filekind(filename)
-
-   if kind=="credential":
-       cred = Credential(filename = filename)
-       cred.dump(dump_parents = options.dump_parents)
-       if options.extract_gids:
-           extract_gids(cred, extract_parents = options.dump_parents)
-   elif kind=="gid":
-       gid = Gid(filename = filename)
-       gid.dump(dump_parents = options.dump_parents)
-   else:
-       print "unknown filekind", kind
+    sfa_logger_goes_to_console()
+    usage = """%prog file1 [ .. filen]
+display info on input files"""
+    parser = OptionParser(usage=usage)
+
+    parser.add_option("-g", "--extract-gids", action="store_true", dest="extract_gids", default=False, help="Extract GIDs from credentials")
+    parser.add_option("-p", "--dump-parents", action="store_true", dest="dump_parents", default=False, help="Show parents")
+    parser.add_option("-e", "--extensions", action="store_true", dest="show_extensions", default="False", help="Show certificate extensions")
+    parser.add_option("-v", "--verbose", action='count', dest='verbose', default=0)
+    (options, args) = parser.parse_args()
+
+    sfa_logger().setLevelFromOptVerbose(options.verbose)
+    if len(args) <= 0:
+        parser.print_help()
+        sys.exit(1)
+    for f in args: 
+        handle_input(f,options)
 
 if __name__=="__main__":
    main()
index 92a9c0d..1365342 100755 (executable)
@@ -15,8 +15,8 @@ from StringIO import StringIO
 from types import StringTypes, ListType
 from optparse import OptionParser
 import zlib
-import logging
 
+from sfa.util.sfalogging import sfa_logger,sfa_logger_goes_to_console
 from sfa.trust.certificate import Keypair, Certificate
 from sfa.trust.gid import GID
 from sfa.trust.credential import Credential
@@ -26,7 +26,6 @@ from sfa.util.namespace import get_leaf, get_authority, hrn_to_urn
 from sfa.util.xmlrpcprotocol import ServerException
 import sfa.util.xmlrpcprotocol as xmlrpcprotocol
 from sfa.util.config import Config
-from sfa.util.sfalogging import console_logger
 
 AGGREGATE_PORT=12346
 CM_PORT=12346
@@ -128,7 +127,8 @@ class Sfi:
         self.authority = None
         self.options = None
         self.hashrequest = False
-        self.logger=console_logger
+        sfa_logger_goes_to_console()
+        self.logger=sfa_logger()
    
     def create_cmd_parser(self, command, additional_cmdargs=None):
         cmdargs = {"list": "name",
@@ -231,14 +231,12 @@ class Sfi:
                          help="user name", metavar="HRN", default=None)
         parser.add_option("-a", "--auth", dest="auth",
                          help="authority name", metavar="HRN", default=None)
-        parser.add_option("-v", "--verbose",
-                         action="store_true", dest="verbose", default=False,
-                         help="verbose mode")
+        parser.add_option("-v", "--verbose", action="count", dest="verbose", default=0,
+                         help="verbose mode - cumulative")
         parser.add_option("-D", "--debug",
                           action="store_true", dest="debug", default=False,
                           help="Debug (xml-rpc) protocol messages")
-        parser.add_option("-p", "--protocol",
-                         dest="protocol", default="xmlrpc",
+        parser.add_option("-p", "--protocol", dest="protocol", default="xmlrpc",
                          help="RPC protocol (xmlrpc or soap)")
         parser.add_option("-k", "--hashrequest",
                          action="store_true", dest="hashrequest", default=False,
@@ -258,7 +256,7 @@ class Sfi:
        except:
           self.logger.critical("Failed to read configuration file %s"%config_file)
           self.logger.info("Make sure to remove the export clauses and to add quotes")
-          if not self.options.verbose:
+          if self.options.verbose==0:
               self.logger.info("Re-run with -v for more details")
           else:
               self.logger.log_exc("Could not read config file %s"%config_file)
@@ -313,8 +311,6 @@ class Sfi:
        self.key_file = key_file
        self.cert_file = cert_file
        self.cert = Certificate(filename=cert_file) 
-       # instruct xmlrpcprotocol to redirect logs to console_logger
-       self.options.client=True
        # Establish connection to server(s)
        self.logger.info("Contacting Registry at: %s"%reg_url)
        self.registry = xmlrpcprotocol.get_server(reg_url, key_file, cert_file, self.options)  
@@ -931,7 +927,7 @@ class Sfi:
         (options, args) = parser.parse_args()
         self.options = options
 
-        if self.options.verbose: self.logger.setLevel(logging.DEBUG)
+        self.logger.setLevelFromOptVerbose(self.options.verbose)
         if options.hashrequest:
             self.hashrequest = True
  
@@ -944,10 +940,7 @@ class Sfi:
 
         self.set_servers()
     
-        self.logger.info("Command %s" % command)
-        self.logger.info("dir %s, user %s, auth %s, reg %s, sm %s" % (
-                self. options.sfi_dir, self.options.user,self.options.auth,
-                self.options.registry, self.options.sm))
+        self.logger.info("Command=%s" % command)
         if command in ("resources"):
             self.logger.debug("resources cmd_opts %s" % cmd_opts.format)
         elif command in ("list", "show", "remove"):
@@ -963,4 +956,4 @@ class Sfi:
         return
     
 if __name__ == "__main__":
-   Sfi().main()
+    Sfi().main()
index b3b041c..5e579ee 100755 (executable)
@@ -76,7 +76,7 @@ start() {
     fi
 
     RETVAL=$?
-    [ $RETVAL -eq 0 ] && touch /var/lock/subsys/sfa
+    [ $RETVAL -eq 0 ] && touch /var/lock/subsys/sfa-server.py
 
 }
 
@@ -84,7 +84,7 @@ stop() {
     action $"Shutting down SFA" killproc sfa-server.py
     RETVAL=$?
 
-    [ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/sfa
+    [ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/sfa-server.py
 }
 
 
@@ -94,13 +94,13 @@ case "$1" in
     reload) reload force ;;
     restart) stop; start ;;
     condrestart)
-       if [ -f /var/lock/subsys/sfa ]; then
+       if [ -f /var/lock/subsys/sfa-server.py ]; then
             stop
             start
        fi
        ;;
     status)
-       status sfa
+       status sfa-server.py
        RETVAL=$?
        ;;
     *)
index 06a1f70..7b50d2a 100644 (file)
@@ -1,8 +1,7 @@
 from __future__ import with_statement 
-from sfa.util.faults import *
-from sfa.util.namespace import *
-from sfa.util.rspec import RSpec
-from sfa.server.registry import Registries
+
+import sys
+import os
 
 import boto
 from boto.ec2.regioninfo import RegionInfo
@@ -12,8 +11,10 @@ from xmlbuilder import XMLBuilder
 from lxml import etree as ET
 from sqlobject import *
 
-import sys
-import os
+from sfa.util.faults import *
+from sfa.util.namespace import urn_to_hrn
+from sfa.util.rspec import RSpec
+from sfa.server.registry import Registries
 
 ##
 # The data structure used to represent a cloud.
index 14168a0..4467026 100644 (file)
@@ -3,7 +3,7 @@
 from sfa.util.rspec import RSpec
 import sys
 import pdb
-from sfa.util.namespace import *
+from sfa.util.namespace import hrn_to_pl_slicename, urn_to_hrn, get_authority
 from sfa.util.rspec import *
 from sfa.util.specdict import *
 from sfa.util.faults import *
index d2507eb..6d12446 100755 (executable)
@@ -1,18 +1,19 @@
-from sfa.util.faults import *
-from sfa.util.namespace import *
-from sfa.util.rspec import RSpec
-from sfa.server.registry import Registries
-from sfa.util.config import Config
-from sfa.plc.nodes import *
 import sys
 
+import socket
+import struct
+
 #The following is not essential
 #from soaplib.wsgi_soap import SimpleWSGISoapApp
 #from soaplib.serializers.primitive import *
 #from soaplib.serializers.clazz import *
 
-import socket
-import struct
+from sfa.util.faults import *
+from sfa.util.namespace import urn_to_hrn
+from sfa.util.rspec import RSpec
+from sfa.server.registry import Registries
+from sfa.util.config import Config
+from sfa.plc.nodes import *
 
 # Message IDs for all the SFA light calls
 # This will be used by the aggrMgr controller
index 0b027e6..d3422c9 100644 (file)
@@ -1,13 +1,11 @@
-### $Id: slices.py 15842 2009-11-22 09:56:13Z anil $
-### $URL: https://svn.planet-lab.org/svn/sfa/trunk/sfa/plc/slices.py $
-
 import datetime
 import time
 import traceback
 import sys
 import re
 from types import StringTypes
-from sfa.util.namespace import *
+
+from sfa.util.namespace import get_authority, urn_to_hrn, slicename_to_hrn, hrn_to_pl_slicename, hrn_to_urn
 from sfa.util.rspec import *
 from sfa.util.specdict import *
 from sfa.util.faults import *
index 2ec4999..d974259 100644 (file)
@@ -1,13 +1,10 @@
-### $Id: slices.py 15842 2009-11-22 09:56:13Z anil $
-### $URL: https://svn.planet-lab.org/svn/sfa/trunk/sfa/plc/slices.py $
-
 import datetime
 import time
 import traceback
 import sys
 
 from types import StringTypes
-from sfa.util.namespace import *
+from sfa.util.namespace import hrn_to_pl_slicename, urn_to_hrn
 from sfa.util.rspec import *
 from sfa.util.specdict import *
 from sfa.util.faults import *
index c26ca4d..5c9506d 100644 (file)
@@ -1,7 +1,8 @@
 import os
 import xmlrpclib
+
 from sfa.util.faults import *
-from sfa.util.namespace import *
+from sfa.util.namespace import urn_to_hrn, hrn_to_pl_slicename
 from sfa.util.sfaticket import SfaTicket
 
 def init_server():
index 4c54e5f..f71915e 100644 (file)
@@ -5,7 +5,7 @@ from sfa.util.record import SfaRecord
 from sfa.util.table import SfaTable
 from sfa.util.record import SfaRecord
 from sfa.trust.gid import GID 
-from sfa.util.namespace import *
+from sfa.util.namespace import get_leaf, get_authority, hrn_to_urn, hrn_to_pl_login_base, urn_to_hrn
 from sfa.trust.credential import *
 from sfa.trust.certificate import *
 from sfa.util.faults import *
index 0c81f37..2c98e24 100644 (file)
@@ -1,16 +1,17 @@
 ### $Id: slices.py 15842 2009-11-22 09:56:13Z anil $
 ### $URL: https://svn.planet-lab.org/svn/sfa/trunk/sfa/plc/slices.py $
 
-import datetime
-import time
-import traceback
 import sys
-from copy import deepcopy
-from lxml import etree
+import time,datetime
 from StringIO import StringIO
 from types import StringTypes
+from copy import deepcopy
+from copy import copy
+from lxml import etree
+
+from sfa.util.sfalogging import sfa_logger
 from sfa.util.rspecHelper import merge_rspecs
-from sfa.util.namespace import *
+from sfa.util.namespace import urn_to_hrn, hrn_to_urn
 from sfa.util.rspec import *
 from sfa.util.specdict import *
 from sfa.util.faults import *
@@ -22,7 +23,6 @@ from sfa.trust.credential import Credential
 from sfa.util.threadmanager import ThreadManager
 import sfa.util.xmlrpcprotocol as xmlrpcprotocol     
 import sfa.plc.peers as peers
-from copy import copy
 
 def get_version():
     version = {}
@@ -396,6 +396,7 @@ def get_rspec(api, creds, options):
                 for request in root.iterfind("./request"):
                     rspec.append(deepcopy(request))
     
+    sfa_logger().debug('get_rspec: rspec=%r'%rspec)
     rspec =  etree.tostring(rspec, xml_declaration=True, pretty_print=True)
     # cache the result
     if api.cache and not xrn:
index 8b45917..e32f9fd 100644 (file)
@@ -1,5 +1,5 @@
 from sfa.util.faults import *
-from sfa.util.namespace import *
+from sfa.util.namespace import urn_to_hrn
 from sfa.util.method import Method
 from sfa.util.parameter import Parameter, Mixed
 from sfa.util.sfatablesRuntime import run_sfatables
index 3ed3b47..8715407 100644 (file)
@@ -2,7 +2,7 @@
 ### $URL: https://svn.planet-lab.org/svn/sfa/trunk/sfa/methods/stop_slice.py $
 
 from sfa.util.faults import *
-from sfa.util.namespace import *
+from sfa.util.namespace import urn_to_hrn
 from sfa.util.method import Method
 from sfa.util.parameter import Parameter, Mixed
 from sfa.trust.auth import Auth
index 9bd5cd1..849da80 100644 (file)
@@ -1,8 +1,7 @@
 #
-from sfa.trust.credential import *
 from sfa.trust.rights import *
 from sfa.util.faults import *
-from sfa.util.namespace import *
+from sfa.util.namespace import urn_to_hrn
 from sfa.util.method import Method
 from sfa.util.parameter import Parameter, Mixed
 from sfa.trust.credential import Credential
index fa8c3a1..647e636 100644 (file)
@@ -1,12 +1,12 @@
 
-from sfa.trust.credential import *
-from sfa.trust.rights import *
 from sfa.util.faults import *
-from sfa.util.namespace import *
+from sfa.util.namespace import urn_to_hrn
 from sfa.util.method import Method
 from sfa.util.parameter import Parameter, Mixed
 from sfa.util.record import SfaRecord
+from sfa.trust.credential import Credential
 from sfa.trust.certificate import Certificate
+from sfa.trust.rights import Right, Rights
 
 class GetSelfCredential(Method):
     """
@@ -33,12 +33,12 @@ class GetSelfCredential(Method):
         """
         GetSelfCredential a degenerate version of GetCredential used by a client
         to get his initial credential when de doesnt have one. This is the same as
-        get_credetial(..., cred = None, ...)
+        GetCredential(..., cred = None, ...)
 
         The registry ensures that the client is the principal that is named by
         (type, name) by comparing the public key in the record's  GID to the
         private key used to encrypt the client side of the HTTPS connection. Thus
-        it is impossible for one principal to retrive another principal's
+        it is impossible for one principal to retrieve another principal's
         credential without having the appropriate private key.
 
         @param type type of object (user | slice | sa | ma | node)
@@ -67,6 +67,11 @@ class GetSelfCredential(Method):
         # authenticate the certificate against the gid in the db
         certificate = Certificate(string=cert)
         if not certificate.is_pubkey(gid.get_pubkey()):
+            for (obj,name) in [ (certificate,"CERT"), (gid,"GID"), ]:
+                self.api.logger.debug("ConnectionKeyGIDMismatch, %s pubkey: %s"%(name,obj.get_pubkey().get_pubkey_string()))
+                self.api.logger.debug("ConnectionKeyGIDMismatch, %s dump: %s"%(name,obj.dump_string()))
+                if hasattr (obj,'filename'): 
+                    self.api.logger.debug("ConnectionKeyGIDMismatch, %s filename: %s"%(name,obj.filename))
             raise ConnectionKeyGIDMismatch(gid.get_subject())
         
         return manager.get_credential(self.api, xrn, type, is_self=True)
index 119ae48..f9b8c22 100644 (file)
@@ -2,7 +2,7 @@
 ### $URL: https://svn.planet-lab.org/svn/sfa/trunk/sfa/methods/get_ticket.py $
 import time
 from sfa.util.faults import *
-from sfa.util.namespace import *
+from sfa.util.namespace import urn_to_hrn
 from sfa.util.method import Method
 from sfa.util.parameter import Parameter, Mixed
 from sfa.trust.auth import Auth
index 8552daf..fef8790 100644 (file)
@@ -1,5 +1,4 @@
 from sfa.util.faults import *
-from sfa.util.namespace import *
 from sfa.util.method import Method
 from sfa.util.parameter import Parameter
 
index 0730f2b..a812c86 100644 (file)
@@ -2,7 +2,7 @@
 ### $URL: https://svn.planet-lab.org/svn/sfa/trunk/sfa/methods/list.py $
 
 from sfa.util.faults import *
-from sfa.util.namespace import *
+from sfa.util.namespace import urn_to_hrn
 from sfa.util.method import Method
 from sfa.util.parameter import Parameter, Mixed
 from sfa.util.record import SfaRecord
index 80b483e..0425853 100644 (file)
@@ -1,5 +1,5 @@
 from sfa.util.faults import *
-from sfa.util.namespace import *
+from sfa.util.namespace import urn_to_hrn
 from sfa.util.method import Method
 from sfa.util.parameter import Parameter, Mixed
 from sfa.trust.credential import Credential
index 236d34f..271bf9e 100644 (file)
@@ -1,8 +1,4 @@
-### $Id: stop_slice.py 17732 2010-04-19 21:10:45Z tmack $
-### $URL: https://svn.planet-lab.org/svn/sfa/trunk/sfa/methods/stop_slice.py $
-
 from sfa.util.faults import *
-from sfa.util.namespace import *
 from sfa.util.method import Method
 from sfa.util.parameter import Parameter, Mixed
 from sfa.trust.auth import Auth
index dae8f6e..51fbe25 100644 (file)
@@ -5,7 +5,7 @@ from sfa.trust.certificate import Keypair, convert_public_key
 from sfa.trust.gid import *
 
 from sfa.util.faults import *
-from sfa.util.namespace import *
+from sfa.util.namespace import get_authority
 from sfa.util.method import Method
 from sfa.util.parameter import Parameter, Mixed
 from sfa.util.record import SfaRecord
index d991159..f13c95d 100644 (file)
@@ -2,7 +2,7 @@
 ### $URL: https://svn.planet-lab.org/svn/sfa/trunk/sfa/methods/remove.py $
 
 from sfa.util.faults import *
-from sfa.util.namespace import *
+from sfa.util.namespace import urn_to_hrn
 from sfa.util.method import Method
 from sfa.util.parameter import Parameter, Mixed
 from sfa.trust.credential import Credential
index ab2063f..1d7c540 100644 (file)
@@ -1,5 +1,5 @@
 from sfa.util.faults import *
-from sfa.util.namespace import *
+from sfa.util.namespace import urn_to_hrn
 from sfa.util.method import Method
 from sfa.util.parameter import Parameter
 from sfa.trust.credential import Credential
index 3f7a61a..d8a536e 100644 (file)
@@ -3,7 +3,7 @@
 import traceback
 import types
 from sfa.util.faults import *
-from sfa.util.namespace import *
+from sfa.util.namespace import urn_to_hrn
 from sfa.util.method import Method
 from sfa.util.parameter import Parameter, Mixed
 from sfa.trust.credential import Credential
index c223bbe..cfca1b9 100644 (file)
@@ -1,5 +1,4 @@
 from sfa.util.faults import *
-from sfa.util.namespace import *
 from sfa.util.method import Method
 from sfa.util.parameter import Parameter
 from sfa.trust.credential import Credential
index f8e3294..00142b6 100644 (file)
@@ -1,5 +1,4 @@
 from sfa.util.faults import *
-from sfa.util.namespace import *
 from sfa.util.method import Method
 from sfa.util.parameter import Parameter
 from sfa.methods.Stop import Stop
index 2233b70..0842c14 100644 (file)
@@ -1,5 +1,5 @@
 from sfa.util.faults import *
-from sfa.util.namespace import *
+from sfa.util.namespace import urn_to_hrn
 from sfa.util.method import Method
 from sfa.util.parameter import Parameter, Mixed
 
index 958e34f..3619106 100644 (file)
@@ -2,7 +2,7 @@
 ### $URL: https://svn.planet-lab.org/svn/sfa/trunk/sfa/methods/stop_slice.py $
 
 from sfa.util.faults import *
-from sfa.util.namespace import *
+from sfa.util.namespace import urn_to_hrn
 from sfa.util.method import Method
 from sfa.util.parameter import Parameter, Mixed
 from sfa.trust.auth import Auth
index c871e05..13106e7 100644 (file)
@@ -2,7 +2,7 @@
 ### $URL: https://svn.planet-lab.org/svn/sfa/trunk/sfa/methods/stop_slice.py $
 
 from sfa.util.faults import *
-from sfa.util.namespace import *
+from sfa.util.namespace import urn_to_hrn
 from sfa.util.method import Method
 from sfa.util.parameter import Parameter, Mixed
 from sfa.trust.auth import Auth
index 37252f2..6c1c5be 100644 (file)
@@ -1,5 +1,4 @@
 from sfa.util.faults import *
-from sfa.util.namespace import *
 from sfa.util.method import Method
 from sfa.util.parameter import Parameter, Mixed
 import sys
index c960974..cfc9daa 100644 (file)
@@ -1,8 +1,6 @@
-### $Id: get_slices.py 14387 2009-07-08 18:19:11Z faiyaza $
-### $URL: https://svn.planet-lab.org/svn/sfa/trunk/sfa/methods/get_aggregates.py $
 from types import StringTypes
 from sfa.util.faults import *
-from sfa.util.namespace import *
+from sfa.util.namespace import urn_to_hrn
 from sfa.util.method import Method
 from sfa.util.parameter import Parameter, Mixed
 from sfa.trust.auth import Auth
index 46af369..5e3f3fd 100644 (file)
@@ -4,7 +4,7 @@ import os
 import tempfile
 import commands
 from sfa.util.faults import *
-from sfa.util.namespace import *
+from sfa.util.namespace import hrn_to_urn
 from sfa.util.method import Method
 from sfa.util.parameter import Parameter, Mixed
 from sfa.trust.auth import Auth
index 358874c..e233143 100644 (file)
@@ -2,7 +2,7 @@
 ### $URL: https://svn.planet-lab.org/svn/sfa/trunk/sfa/methods/get_registries.py $
 from types import StringTypes
 from sfa.util.faults import *
-from sfa.util.namespace import *
+from sfa.util.namespace import urn_to_hrn
 from sfa.util.method import Method
 from sfa.util.parameter import Parameter, Mixed
 from sfa.trust.auth import Auth
index dae8f6e..51fbe25 100644 (file)
@@ -5,7 +5,7 @@ from sfa.trust.certificate import Keypair, convert_public_key
 from sfa.trust.gid import *
 
 from sfa.util.faults import *
-from sfa.util.namespace import *
+from sfa.util.namespace import get_authority
 from sfa.util.method import Method
 from sfa.util.parameter import Parameter, Mixed
 from sfa.util.record import SfaRecord
index cd9026c..21fec61 100644 (file)
@@ -2,7 +2,7 @@
 ### $URL: https://svn.planet-lab.org/svn/sfa/trunk/sfa/methods/reset_slices.py $
 
 from sfa.util.faults import *
-from sfa.util.namespace import *
+from sfa.util.namespace import urn_to_hrn
 from sfa.util.method import Method
 from sfa.util.parameter import Parameter, Mixed
 from sfa.trust.auth import Auth
index 8707405..7e68a6b 100644 (file)
@@ -1,9 +1,6 @@
 #
 # SFA XML-RPC and SOAP interfaces
 #
-### $Id$
-### $URL$
-#
 
 import sys
 import os
@@ -11,16 +8,16 @@ import traceback
 import string
 import xmlrpclib
 
+from sfa.util.faults import *
+from sfa.util.api import *
+from sfa.util.config import *
 from sfa.util.sfalogging import sfa_logger
 import sfa.util.xmlrpcprotocol as xmlrpcprotocol
 from sfa.trust.auth import Auth
-from sfa.util.config import *
-from sfa.util.faults import *
-from sfa.trust.rights import *
-from sfa.trust.credential import *
-from sfa.trust.certificate import *
-from sfa.util.namespace import *
-from sfa.util.api import *
+from sfa.trust.rights import Right, Rights, determine_rights
+from sfa.trust.credential import Credential,Keypair
+from sfa.trust.certificate import Certificate
+from sfa.util.namespace import get_authority, hrn_to_pl_slicename, hrn_to_pl_slicename, hrn_to_urn, slicename_to_hrn, hostname_to_hrn
 from sfa.util.nodemanager import NodeManager
 try:
     from collections import defaultdict
@@ -106,7 +103,7 @@ class SfaAPI(BaseAPI):
 
         self.hrn = self.config.SFA_INTERFACE_HRN
         self.time_format = "%Y-%m-%d %H:%M:%S"
-        self.logger=sfa_logger
+        self.logger=sfa_logger()
 
     def getPLCShell(self):
         self.plauth = {'Username': self.config.SFA_PLC_USER,
index 3e9603b..4293301 100644 (file)
@@ -1,7 +1,7 @@
 from __future__ import with_statement
 import re
 import socket
-from sfa.util.namespace import *
+from sfa.util.namespace import get_authority, hrn_to_pl_slicename
 from sfa.util.faults import *
 from xmlbuilder import XMLBuilder
 from lxml import etree
index 18727c6..0fed065 100755 (executable)
 import getopt
 import sys
 import tempfile
-import logging
 
 from sfa.util.record import *
 from sfa.util.table import SfaTable
-from sfa.util.namespace import *
+from sfa.util.namespace import get_leaf, get_authority, hostname_to_hrn, slicename_to_hrn, email_to_hrn, hrn_to_pl_slicename
 from sfa.util.config import Config
 from sfa.trust.certificate import convert_public_key, Keypair
 from sfa.trust.trustedroot import *
@@ -64,7 +63,7 @@ def main():
     interface_hrn = config.SFA_INTERFACE_HRN
     keys_filename = config.config_path + os.sep + 'person_keys.py' 
     sfaImporter = sfaImport()
-    if config.SFA_API_DEBUG: sfaImporter.logger.setLevel(logging.DEBUG)
+    if config.SFA_API_DEBUG: sfaImporter.logger.setLevelDebug()
     shell = sfaImporter.shell
     plc_auth = sfaImporter.plc_auth 
     table = SfaTable()
@@ -138,7 +137,7 @@ def main():
     # start importing 
     for site in sites:
         site_hrn = interface_hrn + "." + site['login_base']
-        print "Importing site: %s" % site_hrn
+        sfa_logger().info("Importing site: %s" % site_hrn)
 
         # import if hrn is not in list of existing hrns or if the hrn exists
         # but its not a site record
index 4bbf003..8436035 100755 (executable)
@@ -7,27 +7,39 @@
 # is not purged by this tool and may be deleted by a command like 'rm'.
 ##
 
-import getopt
 import sys
+import os
+from optparse import OptionParser
 
 from sfa.trust.hierarchy import *
 from sfa.util.record import *
 from sfa.util.table import SfaTable
-from sfa.util.sfalogging import sfa_import_logger
-
-def process_options():
-
-   (options, args) = getopt.getopt(sys.argv[1:], '', [])
-   for opt in options:
-       name = opt[0]
-       val = opt[1]
+from sfa.util.sfalogging import sfa_logger_goes_to_import,sfa_logger
 
 def main():
-    process_options()
-
-    sfa_import_logger.info("Purging SFA records from database")
-    table = SfaTable()
-    table.sfa_records_purge()
-
+   usage="%prog: trash the registry DB (the 'sfa' table in the 'planetlab5' database)"
+   parser = OptionParser(usage=usage)
+   parser.add_option('-f','--file-system',dest='clean_fs',action='store_true',default=False,
+                     help='Clean up the /var/lib/sfa/authorities area as well')
+   (options,args)=parser.parse_args()
+   if args:
+      parser.print_help()
+      sys.exit(1)
+   sfa_logger_goes_to_import()
+   sfa_logger().info("Purging SFA records from database")
+   table = SfaTable()
+   table.sfa_records_purge()
+   if options.clean_fs:
+      # just remove all files that do not match 'server.key' or 'server.cert'
+      preserved_files = [ 'server.key', 'server.cert']
+      for (dir,_,files) in os.walk('/var/lib/sfa/authorities'):
+         for file in files:
+            if file in preserved_files: continue
+            path=dir+os.sep+file
+            os.unlink(path)
+            if not os.path.exists(path):
+               sfa_logger().info("Unlinked file %s"%path)
+            else:
+               sfa_logger().error("Could not unlink file %s"%path)
 if __name__ == "__main__":
-    main()
+   main()
index 82dc17c..2e8f9d9 100644 (file)
@@ -12,10 +12,11 @@ import getopt
 import sys
 import tempfile
 
-from sfa.util.sfalogging import sfa_import_logger
+from sfa.util.sfalogging import sfa_logger_goes_to_import,sfa_logger
+
 from sfa.util.record import *
 from sfa.util.table import SfaTable
-from sfa.util.namespace import *
+from sfa.util.namespace import get_authority, hrn_to_urn, email_to_hrn
 from sfa.util.config import Config
 from sfa.trust.certificate import convert_public_key, Keypair
 from sfa.trust.trustedroot import *
@@ -50,21 +51,22 @@ def _cleanup_string(str):
 class sfaImport:
 
     def __init__(self):
-        self.logger = sfa_import_logger
-        self.AuthHierarchy = Hierarchy()
-        self.config = Config()
-        self.TrustedRoots = TrustedRootList(Config.get_trustedroots_dir(self.config))
-        self.plc_auth = self.config.get_plc_auth()
-        self.root_auth = self.config.SFA_REGISTRY_ROOT_AUTH
+       sfa_logger_goes_to_import()
+       self.logger = sfa_logger()
+       self.AuthHierarchy = Hierarchy()
+       self.config = Config()
+       self.TrustedRoots = TrustedRootList(Config.get_trustedroots_dir(self.config))
+       self.plc_auth = self.config.get_plc_auth()
+       self.root_auth = self.config.SFA_REGISTRY_ROOT_AUTH
         
-        # connect to planetlab
-        self.shell = None
-        if "Url" in self.plc_auth:
-            from sfa.plc.remoteshell import RemoteShell
-            self.shell = RemoteShell(self.logger)
-        else:
-            import PLC.Shell
-            self.shell = PLC.Shell.Shell(globals = globals())        
+       # connect to planetlab
+       self.shell = None
+       if "Url" in self.plc_auth:
+          from sfa.plc.remoteshell import RemoteShell
+          self.shell = RemoteShell(self.logger)
+       else:
+          import PLC.Shell
+          self.shell = PLC.Shell.Shell(globals = globals())        
 
 
     def create_top_level_auth_records(self, hrn):
@@ -78,7 +80,7 @@ class sfaImport:
 
         # create the authority if it doesnt already exist 
         if not self.AuthHierarchy.auth_exists(urn):
-            self.logger.info("Import: creating top level authorites")
+            self.logger.info("Import: creating top level authorities")
             self.AuthHierarchy.create_auth(urn)
         
         # create the db record if it doesnt already exist    
@@ -100,7 +102,7 @@ class sfaImport:
         if len(hrn) > 64:
             hrn = hrn[:64]
 
-        self.logger.info("Import: importing person " + hrn)
+        self.logger.info("Import: person " + hrn)
         key_ids = []
         if 'key_ids' in person and person['key_ids']:
             key_ids = person["key_ids"]
@@ -113,7 +115,7 @@ class sfaImport:
                 pkey = Keypair(create=True)
         else:
             # the user has no keys
-            self.logger.info("   person " + hrn + " does not have a PL public key")
+            self.logger.warning("Import: person %s does not have a PL public key"%hrn)
             # if a key is unavailable, then we still need to put something in the
             # user's GID. So make one up.
             pkey = Keypair(create=True)
@@ -138,11 +140,11 @@ class sfaImport:
         slicename = _cleanup_string(slicename)
 
         if not slicename:
-            self.logger.error("Import_Slice: failed to parse slice name " + slice['name'])
+            self.logger.error("Import: failed to parse slice name " + slice['name'])
             return
 
         hrn = parent_hrn + "." + slicename
-        self.logger.info("Import: importing slice " + hrn)
+        self.logger.info("Import: slice " + hrn)
 
         pkey = Keypair(create=True)
         urn = hrn_to_urn(hrn, 'slice')
@@ -164,11 +166,11 @@ class sfaImport:
         nodename = _cleanup_string(nodename)
         
         if not nodename:
-            self.logger.error("Import_node: failed to parse node name " + node['hostname'])
+            self.logger.error("Import: failed to parse node name " + node['hostname'])
             return
 
         hrn = parent_hrn + "." + nodename
-        self.logger.info("Import: importing node " + hrn)
+        self.logger.info("Import: node %s" % hrn)
         # ASN.1 will have problems with hrn's longer than 64 characters
         if len(hrn) > 64:
             hrn = hrn[:64]
@@ -195,7 +197,6 @@ class sfaImport:
         plc_auth = self.plc_auth
         sitename = site['login_base']
         sitename = _cleanup_string(sitename)
-        print 'importing site %s' % sitename
         hrn = parent_hrn + "." + sitename
         # Hardcode 'internet2' into the hrn for sites hosting
         # internet2 nodes. This is a special operation for some vini
@@ -209,7 +210,7 @@ class sfaImport:
                 hrn = ".".join([parent_hrn, "internet2", sitename])
 
         urn = hrn_to_urn(hrn, 'authority')
-        self.logger.info("Import: importing site " + hrn)
+        self.logger.info("Import: site " + hrn)
 
         # create the authority
         if not self.AuthHierarchy.auth_exists(urn):
@@ -237,5 +238,5 @@ class sfaImport:
         table = SfaTable()
         record_list = table.find({'type': type, 'hrn': hrn})
         for record in record_list:
-            self.logger.info("Import: Removing record %s %s" % (type, hrn))
+            self.logger.info("Import: removing record %s %s" % (type, hrn))
             table.remove(record)        
index a3c7c1a..9df40c8 100644 (file)
@@ -1,13 +1,10 @@
-### $Id$
-### $URL$
-
 import datetime
 import time
 import traceback
 import sys
 
 from types import StringTypes
-from sfa.util.namespace import *
+from sfa.util.namespace import get_leaf, get_authority, hrn_to_urn, hrn_to_pl_slicename, urn_to_hrn
 from sfa.util.rspec import *
 from sfa.util.specdict import *
 from sfa.util.faults import *
index 51d7d14..99b390a 100644 (file)
@@ -3,7 +3,7 @@
 from sfa.util.rspec import RSpec
 import sys
 import pdb
-from sfa.util.namespace import *
+from sfa.util.namespace import get_authority, hrn_to_pl_slicename, 
 from sfa.util.rspec import *
 from sfa.util.specdict import *
 from sfa.util.faults import *
index a745b6e..4871509 100755 (executable)
@@ -1,9 +1,3 @@
-from sfa.util.faults import *
-from sfa.util.namespace import *
-from sfa.util.rspec import RSpec
-from sfa.server.registry import Registries
-from sfa.util.config import Config
-from sfa.plc.nodes import *
 import sys
 
 #The following is not essential
@@ -14,6 +8,12 @@ import sys
 import socket
 import struct
 
+from sfa.util.faults import *
+from sfa.util.rspec import RSpec
+from sfa.server.registry import Registries
+from sfa.util.config import Config
+from sfa.plc.nodes import *
+
 # Message IDs for all the SFA light calls
 # This will be used by the aggrMgr controller
 SFA_GET_RESOURCES = 101
index 81d8705..3dee184 100644 (file)
@@ -2,8 +2,8 @@
 ### $URL$
 
 
-from sfa.util.server import SfaServer
 from sfa.util.faults import *
+from sfa.util.server import SfaServer
 from sfa.util.namespace import hrn_to_urn
 from sfa.server.interface import Interfaces
 import sfa.util.xmlrpcprotocol as xmlrpcprotocol
@@ -20,8 +20,7 @@ class Aggregate(SfaServer):
     # @param key_file private key filename of registry
     # @param cert_file certificate filename containing public key (could be a GID file)     
     def __init__(self, ip, port, key_file, cert_file):
-        SfaServer.__init__(self, ip, port, key_file, cert_file)
-        self.server.interface = 'aggregate'
+        SfaServer.__init__(self, ip, port, key_file, cert_file,'aggregate')
 
 ##
 # Aggregates is a dictionary of aggregate connections keyed on the aggregate hrn
index 9a1ceea..7ae027d 100644 (file)
@@ -5,7 +5,7 @@
 
 from sfa.util.faults import *
 from sfa.util.storage import *
-from sfa.util.namespace import *
+from sfa.util.namespace import get_authority, hrn_to_urn
 from sfa.trust.gid import GID
 from sfa.util.record import SfaRecord
 import traceback
index 502fea6..bb61bb7 100755 (executable)
@@ -53,5 +53,5 @@ def handler(req):
 
     except Exception, err:
         # Log error in /var/log/httpd/(ssl_)?error_log
-        sfa_logger.log_exc('%r'%err)
+        sfa_logger().log_exc('%r'%err)
         return apache.HTTP_INTERNAL_SERVER_ERROR
index 276005e..0c46084 100755 (executable)
@@ -53,5 +53,5 @@ def handler(req):
 
     except Exception, err:
         # Log error in /var/log/httpd/(ssl_)?error_log
-        sfa_logger.log_exc('%r'%err)
+        sfa_logger().log_exc('%r'%err)
         return apache.HTTP_INTERNAL_SERVER_ERROR
index 1560c80..a28b002 100755 (executable)
@@ -53,5 +53,5 @@ def handler(req):
 
     except Exception, err:
         # Log error in /var/log/httpd/(ssl_)?error_log
-        sfa_logger.log_exc('%r'%err)
+        sfa_logger().log_exc('%r'%err)
         return apache.HTTP_INTERNAL_SERVER_ERROR
index 4e5f80a..b5b1281 100755 (executable)
@@ -52,5 +52,5 @@ def handler(req):
 
     except Exception, err:
         # Log error in /var/log/httpd/(ssl_)?error_log
-        sfa_logger.log_exc("%r"%e)
+        sfa_logger().log_exc("%r"%e)
         return apache.HTTP_INTERNAL_SERVER_ERROR
index fb4f043..1dea183 100644 (file)
@@ -25,9 +25,7 @@ class Registry(SfaServer):
     # @param cert_file certificate filename containing public key (could be a GID file)
     
     def __init__(self, ip, port, key_file, cert_file):
-        SfaServer.__init__(self, ip, port, key_file, cert_file)
-        self.server.interface = 'registry' 
-
+        SfaServer.__init__(self, ip, port, key_file, cert_file,'registry')
 
 ##
 # Registries is a dictionary of registry connections keyed on the registry
index e3d8128..f821f4c 100644 (file)
@@ -3,7 +3,6 @@
 import sys
 import os
 import traceback
-from sfa.util.namespace import *
 from sfa.util.table import SfaTable
 from sfa.util.prefixTree import prefixTree
 from sfa.plc.api import SfaAPI
index e3ad1a2..ad9b499 100755 (executable)
@@ -35,7 +35,6 @@ component_port=12346
 import os, os.path
 import sys
 from optparse import OptionParser
-import logging
 
 from sfa.util.sfalogging import sfa_logger
 from sfa.trust.trustedroot import TrustedRootList
@@ -82,8 +81,8 @@ def init_server_key(server_key_file, server_cert_file, config, hierarchy):
         if not os.path.exists(key_file):
             # if it doesnt exist then this is probably a fresh interface
             # with no records. Generate a random keypair for now
-            sfa_logger.debug("server's public key not found in %s" % key_file)
-            sfa_logger.debug("generating a random server key pair")
+            sfa_logger().debug("server's public key not found in %s" % key_file)
+            sfa_logger().debug("generating a random server key pair")
             key = Keypair(create=True)
             key.save_to_file(server_key_file)
             cert = Certificate(subject=subject)
@@ -170,15 +169,15 @@ def main():
          help="run aggregate manager", default=False)
     parser.add_option("-c", "--component", dest="cm", action="store_true",
          help="run component server", default=False)
-    parser.add_option("-v", "--verbose", dest="verbose", action="store_true", 
-         help="verbose mode", default=False)
+    parser.add_option("-v", "--verbose", action="count", dest="verbose", default=0,
+         help="verbose mode - cumulative")
     parser.add_option("-d", "--daemon", dest="daemon", action="store_true",
          help="Run as daemon.", default=False)
     (options, args) = parser.parse_args()
-    if options.verbose: sfa_logger.setLevel(logging.DEBUG)
+    sfa_logger().setLevelFromOptVerbose(options.verbose)
 
     config = Config()
-    if config.SFA_API_DEBUG: sfa_logger.setLevel(logging.DEBUG)
+    if config.SFA_API_DEBUG: sfa_logger().setLevelDebug()
     hierarchy = Hierarchy()
     server_key_file = os.path.join(hierarchy.basedir, "server.key")
     server_cert_file = os.path.join(hierarchy.basedir, "server.cert")
@@ -216,4 +215,4 @@ if __name__ == "__main__":
     try:
         main()
     except:
-        sfa_logger.log_exc_critical("SFA server is exiting")
+        sfa_logger().log_exc_critical("SFA server is exiting")
index db1c965..80a03a8 100755 (executable)
@@ -5,7 +5,7 @@ import tempfile
 from optparse import OptionParser
 from sfa.util.config import Config
 import sfa.util.xmlrpcprotocol as xmlrpcprotocol
-from sfa.util.namespace import *
+from sfa.util.namespace import hrn_to_pl_slicename, slicename_to_hrn
 from sfa.util.faults import *
 from sfa.trust.certificate import Keypair, Certificate
 from sfa.trust.credential import Credential
index 1194887..8842eae 100644 (file)
@@ -19,5 +19,4 @@ class SliceMgr(SfaServer):
     # @param cert_file certificate filename containing public key (could be a GID file)     
 
     def __init__(self, ip, port, key_file, cert_file, config = "/etc/sfa/sfa_config"):
-        SfaServer.__init__(self, ip, port, key_file, cert_file)
-        self.server.interface = 'slicemgr'      
+        SfaServer.__init__(self, ip, port, key_file, cert_file,'slicemgr')
index b596d8d..3952272 100644 (file)
@@ -1,10 +1,7 @@
 #
 # SfaAPI authentication 
 #
-### $Id$
-### $URL$
-#
-
+import sys
 
 from sfa.trust.certificate import Keypair, Certificate
 from sfa.trust.credential import Credential
@@ -12,9 +9,10 @@ from sfa.trust.trustedroot import TrustedRootList
 from sfa.util.faults import *
 from sfa.trust.hierarchy import Hierarchy
 from sfa.util.config import *
-from sfa.util.namespace import *
+from sfa.util.namespace import get_authority
 from sfa.util.sfaticket import *
-import sys
+
+from sfa.util.sfalogging import sfa_logger
 
 class Auth:
     """
@@ -38,11 +36,14 @@ class Auth:
         valid = []
         if not isinstance(creds, list):
             creds = [creds]
+        sfa_logger().debug("Auth.checkCredentials with %d creds"%len(creds))
         for cred in creds:
             try:
                 self.check(cred, operation, hrn)
                 valid.append(cred)
             except:
+                cred_obj=Credential(string=cred)
+                sfa_logger().debug("failed to validate credential - dump="+cred_obj.dump_string(dump_parents=True))
                 error = sys.exc_info()[:2]
                 continue
             
@@ -57,7 +58,7 @@ class Auth:
         Check the credential against the peer cert (callerGID included 
         in the credential matches the caller that is connected to the 
         HTTPS connection, check if the credential was signed by a 
-        trusted cert and check if the credential is allowd to perform 
+        trusted cert and check if the credential is allowed to perform 
         the specified operation.    
         """
         self.client_cred = Credential(string = cred)
index 450f14d..25bb99a 100644 (file)
@@ -34,9 +34,6 @@
 # This module exports two classes: Keypair and Certificate.
 ##
 #
-### $Id$
-### $URL$
-#
 
 import os
 import tempfile
@@ -79,7 +76,7 @@ def convert_public_key(key):
     try:
         k.load_pubkey_from_file(ssl_fn)
     except:
-        sfa_logger.log_exc("convert_public_key caught exception")
+        sfa_logger().log_exc("convert_public_key caught exception")
         k = None
 
     # remove the temporary files
@@ -125,6 +122,7 @@ class Keypair:
 
     def save_to_file(self, filename):
         open(filename, 'w').write(self.as_pem())
+        self.filename=filename
 
     ##
     # Load the private key from a file. Implicity the private key includes the public key.
@@ -132,6 +130,7 @@ class Keypair:
     def load_from_file(self, filename):
         buffer = open(filename, 'r').read()
         self.load_from_string(buffer)
+        self.filename=filename
 
     ##
     # Load the private key from a string. Implicitly the private key includes the public key.
@@ -170,6 +169,7 @@ class Keypair:
 
         # get the pyopenssl pkey from the pyopenssl x509
         self.key = pyx509.get_pubkey()
+        self.filename=filename
 
     ##
     # Load the public key from a string. No private key is loaded.
@@ -208,7 +208,6 @@ class Keypair:
     def get_openssl_pkey(self):
         return self.key
 
-
     ##
     # Given another Keypair object, return TRUE if the two keys are the same.
 
@@ -230,6 +229,20 @@ class Keypair:
     def compute_hash(self, value):
         return self.sign_string(str(value))
 
+    # only informative
+    def get_filename(self):
+        return getattr(self,'filename',None)
+
+    def dump (self, *args, **kwargs):
+        print self.dump_string(*args, **kwargs)
+
+    def dump_string (self):
+        result=""
+        result += "KEYPAIR: pubkey=%40s..."%self.get_pubkey_string()
+        filename=self.get_filename()
+        if filename: result += "Filename %s\n"%filename
+        return result
+    
 ##
 # The certificate class implements a general purpose X509 certificate, making
 # use of the appropriate pyOpenSSL or M2Crypto abstractions. It also adds
@@ -335,6 +348,7 @@ class Certificate:
         file = open(filename)
         string = file.read()
         self.load_from_string(string)
+        self.filename=filename
 
     ##
     # Save the certificate to a string.
@@ -359,6 +373,7 @@ class Certificate:
             f = open(filename, 'w')
         f.write(string)
         f.close()
+        self.filename=filename
 
     ##
     # Save the certificate to a random file in /tmp/
@@ -466,9 +481,11 @@ class Certificate:
     # Get an X509 extension from the certificate
 
     def get_extension(self, name):
+
         # pyOpenSSL does not have a way to get extensions
         m2x509 = X509.load_cert_string(self.save_to_string())
         value = m2x509.get_ext(name).get_value()
+        
         return value
 
     ##
@@ -503,6 +520,7 @@ class Certificate:
     # Sign the certificate using the issuer private key and issuer subject previous set with set_issuer().
 
     def sign(self):
+        sfa_logger().debug('certificate.sign')
         assert self.cert != None
         assert self.issuerSubject != None
         assert self.issuerKey != None
@@ -542,6 +560,7 @@ class Certificate:
     # @param cert certificate object
 
     def is_signed_by_cert(self, cert):
+        print 'is_signed_by_cert'
         k = cert.get_pubkey()
         result = self.verify(k)
         return result
@@ -587,29 +606,78 @@ class Certificate:
 
         # verify expiration time
         if self.cert.has_expired():
+            sfa_logger().debug("verify_chain: NO our certificate has expired")
             raise CertExpired(self.get_subject(), "client cert")   
         
         # if this cert is signed by a trusted_cert, then we are set
         for trusted_cert in trusted_certs:
             if self.is_signed_by_cert(trusted_cert):
-                sfa_logger.debug("Cert %s signed by trusted cert %s", self.get_subject(), trusted_cert.get_subject())
                 # verify expiration of trusted_cert ?
                 if not trusted_cert.cert.has_expired():
+                    sfa_logger().debug("verify_chain: YES cert %s signed by trusted cert %s"%(
+                            self.get_subject(), trusted_cert.get_subject()))
                     return trusted_cert
                 else:
-                    sfa_logger.debug("Trusted cert %s is expired", trusted_cert.get_subject())       
+                    sfa_logger().debug("verify_chain: NO cert %s is signed by trusted_cert %s, but this is expired..."%(
+                            self.get_subject(),trusted_cert.get_subject()))
+                    raise CertExpired(self.get_subject(),"trusted_cert %s"%trusted_cert.get_subject())
 
         # if there is no parent, then no way to verify the chain
         if not self.parent:
-            sfa_logger.debug("%r has no parent"%self.get_subject())
+            sfa_logger().debug("verify_chain: NO %s has no parent and is not in trusted roots"%self.get_subject())
             raise CertMissingParent(self.get_subject())
 
         # if it wasn't signed by the parent...
         if not self.is_signed_by_cert(self.parent):
-            sfa_logger.debug("%r is not signed by parent"%self.get_subject())
+            sfa_logger().debug("verify_chain: NO %s is not signed by parent"%self.get_subject())
             return CertNotSignedByParent(self.get_subject())
 
         # if the parent isn't verified...
+        sfa_logger().debug("verify_chain: .. %s, -> verifying parent %s",self.get_subject(),self.parent.get_subject())
         self.parent.verify_chain(trusted_certs)
 
         return
+
+    ### more introspection
+    def get_extensions(self):
+        # pyOpenSSL does not have a way to get extensions
+        triples=[]
+        m2x509 = X509.load_cert_string(self.save_to_string())
+        nb_extensions=m2x509.get_ext_count()
+        sfa_logger().debug("X509 had %d extensions"%nb_extensions)
+        for i in range(nb_extensions):
+            ext=m2x509.get_ext_at(i)
+            triples.append( (ext.get_name(), ext.get_value(), ext.get_critical(),) )
+        return triples
+
+    def get_data_names(self):
+        return self.data.keys()
+
+    def get_all_datas (self):
+        triples=self.get_extensions()
+        for name in self.get_data_names(): 
+            triples.append( (name,self.get_data(name),'data',) )
+        return triples
+
+    # only informative
+    def get_filename(self):
+        return getattr(self,'filename',None)
+
+    def dump (self, *args, **kwargs):
+        print self.dump_string(*args, **kwargs)
+
+    def dump_string (self,show_extensions=False):
+        result = ""
+        result += "CERTIFICATE for %s\n"%self.get_subject()
+        result += "Issued by %s\n"%self.get_issuer()
+        filename=self.get_filename()
+        if filename: result += "Filename %s\n"%filename
+        if show_extensions:
+            all_datas=self.get_all_datas()
+            result += " has %d extensions/data attached"%len(all_datas)
+            for (n,v,c) in all_datas:
+                if c=='data':
+                    result += "   data: %s=%s\n"%(n,v)
+                else:
+                    result += "    ext: %s (crit=%s)=<<<%s>>>\n"%(n,c,v)
+        return result
index b46a655..43dc768 100644 (file)
@@ -41,7 +41,7 @@ from sfa.trust.certificate import Keypair
 from sfa.trust.credential_legacy import CredentialLegacy
 from sfa.trust.rights import Right, Rights
 from sfa.trust.gid import GID
-from sfa.util.namespace import *
+from sfa.util.namespace import urn_to_hrn
 
 # 2 weeks, in seconds 
 DEFAULT_CREDENTIAL_LIFETIME = 86400 * 14
@@ -215,6 +215,7 @@ class Credential(object):
                 str = string
             elif filename:
                 str = file(filename).read()
+                self.filename=filename
                 
             if str.strip().startswith("-----"):
                 self.legacy = CredentialLegacy(False,string=str)
@@ -452,6 +453,7 @@ class Credential(object):
             f = open(filename, "w")
         f.write(self.xml)
         f.close()
+        self.filename=filename
 
     def save_to_string(self, save_parents=True):
         if not self.xml:
@@ -661,7 +663,7 @@ class Credential(object):
                 trusted_cert_objects.append(GID(filename=f))
                 ok_trusted_certs.append(f)
             except Exception, exc:
-                sfa_logger.error("Failed to load trusted cert from %s: %r", f, exc)
+                sfa_logger().error("Failed to load trusted cert from %s: %r", f, exc)
         trusted_certs = ok_trusted_certs
 
         # Use legacy verification if this is a legacy credential
@@ -744,7 +746,7 @@ class Credential(object):
         # Maybe should be (hrn, type) = urn_to_hrn(root_cred_signer.get_urn())
         root_cred_signer_type = root_cred_signer.get_type()
         if (root_cred_signer_type == 'authority'):
-            #sfa_logger.debug('Cred signer is an authority')
+            #sfa_logger().debug('Cred signer is an authority')
             # signer is an authority, see if target is in authority's domain
             hrn = root_cred_signer.get_hrn()
             if root_target_gid.get_hrn().startswith(hrn):
@@ -824,28 +826,33 @@ class Credential(object):
         dcred.sign()
 
         return dcred 
-    ##
-    # Dump the contents of a credential to stdout in human-readable format
-    #
-    # @param dump_parents If true, also dump the parent certificates
 
-    def dump(self, dump_parents=False):
-        print "CREDENTIAL", self.get_subject()
+    # only informative
+    def get_filename(self):
+        return getattr(self,'filename',None)
 
-        print "      privs:", self.get_privileges().save_to_string()
-
-        print "  gidCaller:"
+    # @param dump_parents If true, also dump the parent certificates
+    def dump (self, *args, **kwargs):
+        print self.dump_string(*args, **kwargs)
+
+    def dump_string(self, dump_parents=False):
+        result=""
+        result += "CREDENTIAL %s\n" % self.get_subject() 
+        filename=self.get_filename()
+        if filename: result += "Filename %s\n"%filename
+        result += "      privs: %s\n" % self.get_privileges().save_to_string()
         gidCaller = self.get_gid_caller()
         if gidCaller:
-            gidCaller.dump(8, dump_parents)
+            result += "  gidCaller:\n"
+            result += gidCaller.dump_string(8, dump_parents)
 
-        print "  gidObject:"
         gidObject = self.get_gid_object()
         if gidObject:
-            gidObject.dump(8, dump_parents)
-
+            result += "  gidObject:\n"
+            result += gidObject.dump_string(8, dump_parents)
 
         if self.parent and dump_parents:
-            print "PARENT",
-            self.parent.dump_parents()
+            result += "PARENT"
+            result += self.parent.dump_string(dump_parents)
+        return result
 
index b868f2d..8ba90b2 100644 (file)
@@ -223,24 +223,29 @@ class CredentialLegacy(Certificate):
     #
     # @param dump_parents If true, also dump the parent certificates
 
-    def dump(self, dump_parents=False):
-        print "CREDENTIAL", self.get_subject()
+    def dump(self, *args, **kwargs):
+        print self.dump_string(*args,**kwargs)
 
-        print "      privs:", self.get_privileges().save_to_string()
+    def dump_string(self, dump_parents=False):
+        result=""
+        result += "CREDENTIAL %s\n" % self.get_subject()
+
+        result += "      privs: %s\n" % self.get_privileges().save_to_string()
 
-        print "  gidCaller:"
         gidCaller = self.get_gid_caller()
         if gidCaller:
+            result += "  gidCaller:\n"
             gidCaller.dump(8, dump_parents)
 
-        print "  gidObject:"
         gidObject = self.get_gid_object()
         if gidObject:
-            gidObject.dump(8, dump_parents)
+            result += "  gidObject:\n"
+            result += gidObject.dump_string(8, dump_parents)
 
-        print "   delegate:", self.get_delegate()
+        result += "   delegate: %s" % self.get_delegate()
 
         if self.parent and dump_parents:
-           print "PARENT",
-           self.parent.dump(dump_parents)
+            result += "PARENT\n"
+            result += self.parent.dump_string(dump_parents)
 
+        return result
index 6adfec5..5976b66 100644 (file)
@@ -32,7 +32,7 @@ import uuid
 
 from sfa.util.sfalogging import sfa_logger
 from sfa.trust.certificate import Certificate
-from sfa.util.namespace import *
+from sfa.util.namespace import hrn_to_urn, urn_to_hrn
 
 ##
 # Create a new uuid. Returns the UUID as a string.
@@ -82,7 +82,7 @@ class GID(Certificate):
         
         Certificate.__init__(self, create, subject, string, filename)
         if subject:
-            sfa_logger.debug("Creating GID for subject: %s" % subject)
+            sfa_logger().debug("Creating GID for subject: %s" % subject)
         if uuid:
             self.uuid = int(uuid)
         if hrn:
@@ -178,14 +178,21 @@ class GID(Certificate):
     # @param indent specifies a number of spaces to indent the output
     # @param dump_parents If true, also dump the parents of the GID
 
-    def dump(self, indent=0, dump_parents=False):
-        print " "*indent, " hrn:", self.get_hrn()
-        print " "*indent, " urn:", self.get_urn()
-        print " "*indent, "uuid:", self.get_uuid()
+    def dump(self, *args, **kwargs):
+        print self.dump_string(*args,**kwargs)
+
+    def dump_string(self, indent=0, dump_parents=False):
+        result="GID\n"
+        result += " "*indent + "hrn:" + str(self.get_hrn()) +"\n"
+        result += " "*indent + "urn:" + str(self.get_urn()) +"\n"
+        result += " "*indent + "uuid:" + str(self.get_uuid()) + "\n"
+        filename=self.get_filename()
+        if filename: result += "Filename %s\n"%filename
 
         if self.parent and dump_parents:
-            print " "*indent, "parent:"
-            self.parent.dump(indent+4, dump_parents)
+            result += " "*indent + "parent:\n"
+            result += self.parent.dump_string(indent+4, dump_parents)
+        return result
 
     ##
     # Verify the chain of authenticity of the GID. First perform the checks
index 1f8afcf..0ae7e4b 100644 (file)
 #      *.DBINFO - database info
 ##
 
-### $Id$
-### $URL$
-
 import os
 
 from sfa.util.sfalogging import sfa_logger
 from sfa.trust.certificate import Keypair
 from sfa.trust.credential import *
 from sfa.trust.gid import GID, create_uuid
-from sfa.util.namespace import *
+from sfa.util.namespace import get_leaf, get_authority, hrn_to_urn, urn_to_hrn
 from sfa.util.config import Config
 from sfa.util.sfaticket import SfaTicket
 
@@ -161,7 +158,7 @@ class Hierarchy:
 
     def create_auth(self, xrn, create_parents=False):
         hrn, type = urn_to_hrn(xrn)
-        sfa_logger.debug("Hierarchy: creating authority: " + hrn)
+        sfa_logger().debug("Hierarchy: creating authority: " + hrn)
 
         # create the parent authority if necessary
         parent_hrn = get_authority(hrn)
@@ -181,7 +178,7 @@ class Hierarchy:
                 pass
 
         if os.path.exists(privkey_filename):
-            sfa_logger.debug("using existing key %r for authority %r"%(privkey_filename,hrn))
+            sfa_logger().debug("using existing key %r for authority %r"%(privkey_filename,hrn))
             pkey = Keypair(filename = privkey_filename)
         else:
             pkey = Keypair(create = True)
@@ -206,8 +203,8 @@ class Hierarchy:
 
     def get_auth_info(self, xrn):
         hrn, type = urn_to_hrn(xrn)
-        sfa_logger.debug("Hierarchy: xrn=%s, getting authority for hrn=%s"%(xrn,hrn))
         if not self.auth_exists(hrn):
+            sfa_logger().warning("Hierarchy: mising authority - xrn=%s, hrn=%s"%(xrn,hrn))
             raise MissingAuthority(hrn)
 
         (directory, gid_filename, privkey_filename, dbinfo_filename) = \
index 7ae9442..f2c51bf 100644 (file)
@@ -179,21 +179,21 @@ class PostgreSQL:
 
             if not params:
                 if self.debug:
-                    sfa_logger.debug('execute0 %r'%query)
+                    sfa_logger().debug('execute0 %r'%query)
                 cursor.execute(query)
             elif isinstance(params,dict):
                 if self.debug:
-                    sfa_logger.debug('execute-dict: params=[%r] query=[%r]'%(params,query%params))
+                    sfa_logger().debug('execute-dict: params=[%r] query=[%r]'%(params,query%params))
                 cursor.execute(query,params)
             elif isinstance(params,tuple) and len(params)==1:
                 if self.debug:
-                    sfa_logger.debug('execute-tuple %r'%(query%params[0]))
+                    sfa_logger().debug('execute-tuple %r'%(query%params[0]))
                 cursor.execute(query,params[0])
             else:
                 param_seq=(params,)
                 if self.debug:
                     for params in param_seq:
-                        sfa_logger.debug('executemany %r'%(query%params))
+                        sfa_logger().debug('executemany %r'%(query%params))
                 cursor.executemany(query, param_seq)
             (self.rowcount, self.description, self.lastrowid) = \
                             (cursor.rowcount, cursor.description, cursor.lastrowid)
@@ -203,11 +203,11 @@ class PostgreSQL:
             except:
                 pass
             uuid = commands.getoutput("uuidgen")
-            sfa_logger.error("Database error %s:" % uuid)
-            sfa_logger.error("Exception=%r"%e)
-            sfa_logger.error("Query=%r"%query)
-            sfa_logger.error("Params=%r"%pformat(params))
-            sfa_logger.log_exc("PostgreSQL.execute caught exception")
+            sfa_logger().error("Database error %s:" % uuid)
+            sfa_logger().error("Exception=%r"%e)
+            sfa_logger().error("Query=%r"%query)
+            sfa_logger().error("Params=%r"%pformat(params))
+            sfa_logger().log_exc("PostgreSQL.execute caught exception")
             raise SfaDBError("Please contact support: %s" % str(e))
 
         return cursor
index 1e131be..f9aed1c 100644 (file)
@@ -1,9 +1,6 @@
 #
 # SFA XML-RPC and SOAP interfaces
 #
-### $Id$
-### $URL$
-#
 
 import sys
 import os
@@ -17,7 +14,6 @@ from sfa.util.config import *
 from sfa.util.faults import *
 from sfa.trust.credential import *
 from sfa.trust.certificate import *
-from sfa.util.namespace import *
 
 # See "2.2 Characters" in the XML specification:
 #
@@ -242,7 +238,7 @@ class BaseAPI:
         except SfaFault, fault:
             result = fault 
         except Exception, fault:
-            sfa_logger.log_exc("BaseAPI.handle has caught Exception")
+            sfa_logger().log_exc("BaseAPI.handle has caught Exception")
             result = SfaAPIError(fault)
 
 
index 50c312e..c12104b 100644 (file)
@@ -74,7 +74,7 @@ class SecureXMLRpcRequestHandler(SimpleXMLRPCServer.SimpleXMLRPCRequestHandler):
             # internal error, report as HTTP server error
             self.send_response(500)
             self.end_headers()
-            sfa_logger.log_exc("componentserver.SecureXMLRpcRequestHandler.do_POST")
+            sfa_logger().log_exc("componentserver.SecureXMLRpcRequestHandler.do_POST")
         else:
             # got a valid XML RPC response
             self.send_response(200)
index ec9440e..125629d 100644 (file)
@@ -92,7 +92,7 @@ class Method (object):
 
             if self.api.config.SFA_API_DEBUG or hasattr(self, 'message'):
                 msg=getattr(self,'message',"method %s completed in %02f s"%(methodname,runtime))
-                sfa_logger.info(msg)
+                sfa_logger().debug(msg)
 
             return result
 
@@ -103,7 +103,7 @@ class Method (object):
             # Prepend caller and method name to expected faults
             fault.faultString = caller + ": " +  self.name + ": " + fault.faultString
             runtime = time.time() - start
-            sfa_logger.log_exc("Method %s raised an exception"%self.name) 
+            sfa_logger().log_exc("Method %s raised an exception"%self.name) 
             raise fault
 
 
index 3251b99..7e3c03c 100644 (file)
@@ -1,5 +1,3 @@
-### $Id$
-### $URL$
 import re
 from sfa.util.faults import *
 URN_PREFIX = "urn:publicid:IDN"
index 87360be..6cb9d37 100644 (file)
@@ -13,7 +13,7 @@ from sfa.trust.gid import *
 
 from sfa.util.rspec import *
 from sfa.util.parameter import *
-from sfa.util.namespace import *
+from sfa.util.namespace import get_authority
 from sfa.util.row import Row
 
 class SfaRecord(Row):
index aab5592..486332c 100644 (file)
@@ -235,11 +235,11 @@ class RSpec:
             except Exception, e:
                 # logging.debug("%s: web file not found" % xsdURI)
                 # logging.debug("Using local file %s" % self.xsd")
-                sfa_logger.log_exc("rspec.parseXSD: can't find %s on the web. Continuing." % xsdURI)
+                sfa_logger().log_exc("rspec.parseXSD: can't find %s on the web. Continuing." % xsdURI)
         if not schemaDom:
             if os.path.exists(xsdURI):
                 # logging.debug("using local copy.")
-                sfa_logger.debug("rspec.parseXSD: Using local %s" % xsdURI)
+                sfa_logger().debug("rspec.parseXSD: Using local %s" % xsdURI)
                 schemaDom = minidom.parse(xsdURI)
             else:
                 raise Exception("rspec.parseXSD: can't find xsd locally")
index 2d8e13b..b5a966d 100644 (file)
@@ -25,6 +25,8 @@ from sfa.trust.credential import *
 from sfa.util.faults import *
 from sfa.plc.api import SfaAPI
 from sfa.util.cache import Cache 
+from sfa.util.sfalogging import sfa_logger
+
 ##
 # Verification callback for pyOpenSSL. We do our own checking of keys because
 # we have our own authentication spec. Thus we disable several of the normal
@@ -109,7 +111,7 @@ class SecureXMLRpcRequestHandler(SimpleXMLRPCServer.SimpleXMLRPCRequestHandler):
         except Exception, fault:
             # This should only happen if the module is buggy
             # internal error, report as HTTP server error
-            sfa_error.log_exc("server.do_POST")
+            sfa_logger().log_exc("server.do_POST")
             response = self.api.prepare_response(fault)
             #self.send_response(500)
             #self.end_headers()
@@ -133,6 +135,7 @@ class SecureXMLRPCServer(BaseHTTPServer.HTTPServer,SimpleXMLRPCServer.SimpleXMLR
 
         It it very similar to SimpleXMLRPCServer but it uses HTTPS for transporting XML data.
         """
+        sfa_logger().debug("SecureXMLRPCServer.__init__, server_address=%s, cert_file=%s"%(server_address,cert_file))
         self.logRequests = logRequests
         self.interface = None
         self.key_file = key_file
@@ -165,6 +168,7 @@ class SecureXMLRPCServer(BaseHTTPServer.HTTPServer,SimpleXMLRPCServer.SimpleXMLR
     # the client.
 
     def _dispatch(self, method, params):
+        sfa_logger().debug("SecureXMLRPCServer._dispatch, method=%s"%method)
         try:
             return SimpleXMLRPCServer.SimpleXMLRPCDispatcher._dispatch(self, method, params)
         except:
@@ -245,15 +249,16 @@ class SfaServer(threading.Thread):
     # @param cert_file certificate filename containing public key 
     #   (could be a GID file)
 
-    def __init__(self, ip, port, key_file, cert_file):
+    def __init__(self, ip, port, key_file, cert_file,interface):
         threading.Thread.__init__(self)
         self.key = Keypair(filename = key_file)
         self.cert = Certificate(filename = cert_file)
         #self.server = SecureXMLRPCServer((ip, port), SecureXMLRpcRequestHandler, key_file, cert_file)
         self.server = ThreadedServer((ip, port), SecureXMLRpcRequestHandler, key_file, cert_file)
+        self.server.interface=interface
         self.trusted_cert_list = None
         self.register_functions()
-
+        sfa_logger().info("Starting SfaServer, interface=%s"%interface)
 
     ##
     # Register functions that will be served by the XMLRPC server. This
index 720e57d..9d43d91 100755 (executable)
@@ -1,9 +1,15 @@
 #!/usr/bin/python
 
-import os
+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):
@@ -11,7 +17,7 @@ class _SfaLogger:
         if not logfile:
             loggername='console'
             handler=logging.StreamHandler()
-            handler.setFormatter(logging.Formatter("%(message)s"))
+            handler.setFormatter(logging.Formatter("%(levelname)s %(message)s"))
         else:
             if not loggername:
                 loggername=os.path.basename(logfile)
@@ -27,10 +33,26 @@ class _SfaLogger:
         self.logger=logging.getLogger(loggername)
         self.logger.setLevel(level)
         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)
+
     ####################
     def wrap(fun):
         def wrapped(self,msg,*args,**kwds):
@@ -65,9 +87,30 @@ class _SfaLogger:
         self.debug("%s BEG STACK"%message+"\n"+to_log)
         self.debug("%s END STACK"%message)
 
-sfa_logger=_SfaLogger(logfile='/var/log/sfa.log')
-sfa_import_logger=_SfaLogger(logfile='/var/log/sfa_import.log')
-console_logger=_SfaLogger()
+####################
+# import-related operations go in this file
+_import_logger=_SfaLogger(logfile='/var/log/sfa_import.log')
+# servers log into /var/log/sfa.log
+_server_logger=_SfaLogger(logfile='/var/log/sfa.log')
+# clients use the console
+_console_logger=_SfaLogger()
+
+# default is to use the server-side logger
+_the_logger=_server_logger
+
+# clients would change the default by issuing one of these call
+def sfa_logger_goes_to_console():
+    current_module=sys.modules[globals()['__name__']]
+    current_module._the_logger=_console_logger
+
+# clients would change the default by issuing one of these call
+def sfa_logger_goes_to_import():
+    current_module=sys.modules[globals()['__name__']]
+    current_module._logger=_import_logger
+
+# this is how to retrieve the 'right' logger
+def sfa_logger():
+    return _the_logger
 
 ########################################
 import time
@@ -105,12 +148,16 @@ if __name__ == '__main__':
     logger.setLevel(logging.DEBUG)
     logger.debug("logger.debug again")
     
-    @profile(console_logger)
+    sfa_logger_goes_to_console()
+    my_logger=sfa_logger()
+    my_logger.info("redirected to console")
+
+    @profile(my_logger)
     def sleep(seconds = 1):
         time.sleep(seconds)
 
-    
-    console_logger.info('console.info')
+    my_logger.info('console.info')
     sleep(0.5)
-    console_logger.setLevel(logging.DEBUG)
+    my_logger.setLevel(logging.DEBUG)
     sleep(0.25)
+
index d1fbe1e..43c957a 100644 (file)
@@ -2,7 +2,7 @@
 
 import xmlrpclib
 
-from sfa.util.sfalogging import sfa_logger, console_logger
+from sfa.util.sfalogging import sfa_logger
 
 ##
 # ServerException, ExceptionUnmarshaller
@@ -53,14 +53,10 @@ class XMLRPCServerProxy(xmlrpclib.ServerProxy):
         verbose = False
         if self.options and self.options.debug:
             verbose = True
-        if self.options and hasattr(self.options,'client'):
-            XMLRPCServerProxy.logger=console_logger
-        else:
-            XMLRPCServerProxy.logger=sfa_logger
         xmlrpclib.ServerProxy.__init__(self, url, transport, allow_none=allow_none, verbose=verbose)
 
     def __getattr__(self, attr):
-        XMLRPCServerProxy.logger.debug("Calling xml-rpc method:%s"%attr)
+        sfa_logger().debug("Calling xml-rpc method:%s"%attr)
         return xmlrpclib.ServerProxy.__getattr__(self, attr)