sfadump more usable
[sfa.git] / sfa / server / sfa_component_setup.py
index 779b8bf..80a03a8 100755 (executable)
@@ -5,12 +5,27 @@ import tempfile
 from optparse import OptionParser
 from sfa.util.config import Config
 import sfa.util.xmlrpcprotocol as xmlrpcprotocol
 from optparse import OptionParser
 from sfa.util.config import Config
 import sfa.util.xmlrpcprotocol as xmlrpcprotocol
-import sfa.util.misc as misc
+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
 from sfa.trust.gid import GID
 from sfa.trust.hierarchy import Hierarchy
 
 from sfa.trust.certificate import Keypair, Certificate
 from sfa.trust.credential import Credential
 from sfa.trust.gid import GID
 from sfa.trust.hierarchy import Hierarchy
 
+KEYDIR = "/var/lib/sfa/"
+CONFDIR = "/etc/sfa/"
+
+def handle_gid_mismatch_exception(f):
+    def wrapper(*args, **kwds):
+        try: return f(*args, **kwds)
+        except ConnectionKeyGIDMismatch:
+            # clean regen server keypair and try again
+            print "cleaning keys and trying again"
+            clean_key_cred()
+            return f(args, kwds)
+
+    return wrapper
+
 def get_server(url=None, port=None, keyfile=None, certfile=None,verbose=False):
     """
     returns an xmlrpc connection to the service a the specified 
 def get_server(url=None, port=None, keyfile=None, certfile=None,verbose=False):
     """
     returns an xmlrpc connection to the service a the specified 
@@ -45,13 +60,33 @@ def create_default_dirs():
     for dir in all_dirs:
         if not os.path.exists(dir):
             os.makedirs(dir)
     for dir in all_dirs:
         if not os.path.exists(dir):
             os.makedirs(dir)
+
+def has_node_key():
+    key_file = KEYDIR + os.sep + 'server.key'
+    return os.path.exists(key_file) 
+
+def clean_key_cred():
+    """
+    remove the existing keypair and cred  and generate new ones
+    """
+    files = ["server.key", "server.cert", "node.cred"]
+    for f in files:
+        filepath = KEYDIR + os.sep + f
+        if os.path.isfile(filepath):
+            os.unlink(f)
+   
+    # install the new key pair
+    # get_credential will take care of generating the new keypair
+    # and credential 
+    get_credential()
+    
              
 def get_node_key(registry=None, verbose=False):
     # this call requires no authentication, 
     # so we can generate a random keypair here
     subject="component"
              
 def get_node_key(registry=None, verbose=False):
     # this call requires no authentication, 
     # so we can generate a random keypair here
     subject="component"
-    keyfile = tempfile.mktemp()
-    certfile = tempfile.mktemp()
+    (kfd, keyfile) = tempfile.mkstemp()
+    (cfd, certfile) = tempfile.mkstemp()
     key = Keypair(create=True)
     key.save_to_file(keyfile)
     cert = Certificate(subject=subject)
     key = Keypair(create=True)
     key.save_to_file(keyfile)
     cert = Certificate(subject=subject)
@@ -74,8 +109,9 @@ def create_server_keypair(keyfile=None, certfile=None, hrn="component", verbose=
     cert.set_pubkey(key)
     cert.sign()
     cert.save_to_file(certfile, save_parents=True)       
     cert.set_pubkey(key)
     cert.sign()
     cert.save_to_file(certfile, save_parents=True)       
-        
-def get_credential(registry=None, verbose=False):
+
+@handle_gid_mismatch_exception
+def get_credential(registry=None, force=False, verbose=False):
     config = Config()
     hierarchy = Hierarchy()
     key_dir= hierarchy.basedir
     config = Config()
     hierarchy = Hierarchy()
     key_dir= hierarchy.basedir
@@ -83,7 +119,7 @@ def get_credential(registry=None, verbose=False):
     config_dir = config.config_path
     credfile = data_dir + os.sep + 'node.cred'
     # check for existing credential
     config_dir = config.config_path
     credfile = data_dir + os.sep + 'node.cred'
     # check for existing credential
-    if os.path.exists(credfile):
+    if not force and os.path.exists(credfile):
         if verbose:
             print "Loading Credential from %(credfile)s " % locals()  
         cred = Credential(filename=credfile).save_to_string(save_parents=True)
         if verbose:
             print "Loading Credential from %(credfile)s " % locals()  
         cred = Credential(filename=credfile).save_to_string(save_parents=True)
@@ -110,11 +146,12 @@ def get_credential(registry=None, verbose=False):
         registry = get_server(url=registry, keyfile=keyfile, certfile=certfile)
         cert = Certificate(filename=certfile)
         cert_str = cert.save_to_string(save_parents=True)
         registry = get_server(url=registry, keyfile=keyfile, certfile=certfile)
         cert = Certificate(filename=certfile)
         cert_str = cert.save_to_string(save_parents=True)
-        cred = registry.get_self_credential(cert_str, 'node', hrn)    
+        cred = registry.GetSelfCredential(cert_str, 'node', hrn)
         Credential(string=cred).save_to_file(credfile, save_parents=True)
     
     return cred
 
         Credential(string=cred).save_to_file(credfile, save_parents=True)
     
     return cred
 
+@handle_gid_mismatch_exception
 def get_trusted_certs(registry=None, verbose=False):
     """
     refresh our list of trusted certs.
 def get_trusted_certs(registry=None, verbose=False):
     """
     refresh our list of trusted certs.
@@ -142,8 +179,9 @@ def get_trusted_certs(registry=None, verbose=False):
     for gid_str in trusted_certs:
         gid = GID(string=gid_str)
         gid.decode()
     for gid_str in trusted_certs:
         gid = GID(string=gid_str)
         gid.decode()
-        trusted_gid_names.append(gid.get_hrn())
-        gid_filename = trusted_certs_dir + os.sep + gid.get_hrn() + ".gid"
+        relative_filename = gid.get_hrn() + ".gid"
+        trusted_gid_names.append(relative_filename)
+        gid_filename = trusted_certs_dir + os.sep + relative_filename
         if verbose:
             print "Writing GID for %s as %s" % (gid.get_hrn(), gid_filename) 
         gid.save_to_file(gid_filename, save_parents=True)
         if verbose:
             print "Writing GID for %s as %s" % (gid.get_hrn(), gid_filename) 
         gid.save_to_file(gid_filename, save_parents=True)
@@ -156,6 +194,7 @@ def get_trusted_certs(registry=None, verbose=False):
                 print "Removing old gid ", gid_name
             os.unlink(trusted_certs_dir + os.sep + gid_name)                     
 
                 print "Removing old gid ", gid_name
             os.unlink(trusted_certs_dir + os.sep + gid_name)                     
 
+@handle_gid_mismatch_exception
 def get_gids(registry=None, verbose=False):
     """
     Get the gid for all instantiated slices on this node and store it
 def get_gids(registry=None, verbose=False):
     """
     Get the gid for all instantiated slices on this node and store it
@@ -183,20 +222,35 @@ def get_gids(registry=None, verbose=False):
     # get a list of slices on this node
     from sfa.plc.api import ComponentAPI
     api = ComponentAPI()
     # get a list of slices on this node
     from sfa.plc.api import ComponentAPI
     api = ComponentAPI()
-    slicenames = api.nodemanager.GetXIDs().keys()   
-    slicename_to_hrn = lambda name: ".".join([interface_hrn, name.replace('_', '.')])
-    hrns = map(slicename_to_hrn, slicenames)
+    xids_tuple = api.nodemanager.GetXIDs()
+    slices = eval(xids_tuple[1])
+    slicenames = slices.keys()
 
 
+    # generate a list of slices that dont have gids installed
+    slices_without_gids = []
+    for slicename in slicenames:
+        if not os.path.isfile("/vservers/%s/etc/slice.gid" % slicename) \
+        or not os.path.isfile("/vservers/%s/etc/node.gid" % slicename):
+            slices_without_gids.append(slicename) 
+    
+    # convert slicenames to hrns
+    hrns = [slicename_to_hrn(interface_hrn, slicename) \
+            for slicename in slices_without_gids]
+    
+    # exit if there are no gids to install
+    if not hrns:
+        return
+        
     if verbose:
         print "Getting gids for slices on this node from registry"  
     # get the gids
     # and save them in the right palce
     if verbose:
         print "Getting gids for slices on this node from registry"  
     # get the gids
     # and save them in the right palce
-    records = registry.get_gids(cred, hrns)
+    records = registry.GetGids(hrns, cred)
     for record in records:
         # if this isnt a slice record skip it
         if not record['type'] == 'slice':
             continue
     for record in records:
         # if this isnt a slice record skip it
         if not record['type'] == 'slice':
             continue
-        slicename = misc.hrn_to_pl_slicename(record['hrn'])
+        slicename = hrn_to_pl_slicename(record['hrn'])
         # if this slice isnt really instatiated skip it
         if not os.path.exists("/vservers/%(slicename)s" % locals()):
             continue
         # if this slice isnt really instatiated skip it
         if not os.path.exists("/vservers/%(slicename)s" % locals()):
             continue