Merge branch 'master' into senslab2
[sfa.git] / sfa / client / sfaadmin.py
index 48d117f..ffe7a4b 100755 (executable)
@@ -12,8 +12,15 @@ from sfa.client.sfi import save_records_to_file
 from sfa.trust.hierarchy import Hierarchy
 from sfa.trust.gid import GID
 
+from sfa.client.candidates import Candidates
+
 pprinter = PrettyPrinter(indent=4)
 
+try:
+    help_basedir=Hierarchy().basedir
+except:
+    help_basedir='*unable to locate Hierarchy().basedir'
+
 def optparse_listvalue_callback(option, opt, value, parser):
     setattr(parser.values, option.dest, value.split(','))
 
@@ -25,11 +32,11 @@ def args(*args, **kwargs):
 
 class Commands(object):
     def _get_commands(self):
-        available_methods = []
+        command_names = []
         for attrib in dir(self):
             if callable(getattr(self, attrib)) and not attrib.startswith('_'):
-                available_methods.append(attrib)
-        return available_methods         
+                command_names.append(attrib)
+        return command_names
 
 
 class RegistryCommands(Commands):
@@ -43,10 +50,13 @@ class RegistryCommands(Commands):
 
     @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='authority to list (hrn/urn - mandatory)') 
     @args('-t', '--type', dest='type', metavar='<type>', help='object type', default=None) 
-    def list(self, xrn, type=None):
+    @args('-r', '--recursive', dest='recursive', metavar='<recursive>', help='list all child records', 
+          action='store_true', default=False) 
+    def list(self, xrn, type=None, recursive=False):
         """List names registered at a given authority - possibly filtered by type"""
         xrn = Xrn(xrn, type) 
-        records = self.api.manager.List(self.api, xrn.get_hrn())
+        options = {'recursive': recursive}    
+        records = self.api.manager.List(self.api, xrn.get_hrn(), options=options)
         for record in records:
             if not type or record['type'] == type:
                 print "%s (%s)" % (record['hrn'], record['type'])
@@ -59,7 +69,7 @@ class RegistryCommands(Commands):
           choices=('text', 'xml', 'simple'), help='display record in different formats') 
     def show(self, xrn, type=None, format=None, outfile=None):
         """Display details for a registered object"""
-        records = self.api.manager.Resolve(self.api, xrn, type, True)
+        records = self.api.manager.Resolve(self.api, xrn, type, details=True)
         for record in records:
             sfa_record = Record(dict=record)
             sfa_record.dump(format) 
@@ -67,8 +77,10 @@ class RegistryCommands(Commands):
             save_records_to_file(outfile, records)  
 
 
-    def _record_dict(self, xrn=None, type=None, url=None, key=None, \
-                     description=None, slices='', researchers=''):              
+    def _record_dict(self, xrn=None, type=None, 
+                     url=None, description=None, email='', 
+                     key=None, 
+                     slices=[], researchers=[], pis=[]):
         record_dict = {}
         if xrn:
             if type:
@@ -80,6 +92,8 @@ class RegistryCommands(Commands):
             record_dict['type'] = xrn.get_type()
         if url:
             record_dict['url'] = url
+        if description:
+            record_dict['description'] = description
         if key:
             try:
                 pubkey = open(key, 'r').read()
@@ -89,16 +103,21 @@ class RegistryCommands(Commands):
         if slices:
             record_dict['slices'] = slices
         if researchers:
-            record_dict['researchers'] = researchers
-        if description:
-            record_dict['description'] = description
+            record_dict['researcher'] = researchers
+        if email:
+            record_dict['email'] = email
+        if pis:
+            record_dict['pi'] = pis
         return record_dict
 
     @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn (mandatory)') 
     @args('-t', '--type', dest='type', metavar='<type>', help='object type', default=None) 
-    @args('-u', '--url', dest='url', metavar='<url>', help='URL', default=None)
+    @args('-e', '--email', dest='email', default="",
+          help="email (mandatory for users)")
+    @args('-u', '--url', dest='url', metavar='<url>', default=None,
+          help="URL, useful for slices")
     @args('-d', '--description', dest='description', metavar='<description>', 
-          help='Description', default=None)
+          help='Description, useful for slices', default=None)
     @args('-k', '--key', dest='key', metavar='<key>', help='public key string or file', 
           default=None)
     @args('-s', '--slices', dest='slices', metavar='<slices>', help='slice xrns', 
@@ -109,10 +128,10 @@ class RegistryCommands(Commands):
           help='Principal Investigators/Project Managers ', 
           default='', type="str", action='callback', callback=optparse_listvalue_callback)
     def register(self, xrn, type=None, url=None, description=None, key=None, slices='', 
-                 pis='', researchers=''):
-        """Create a new Registry recory"""
+                 pis='', researchers='',email=''):
+        """Create a new Registry record"""
         record_dict = self._record_dict(xrn=xrn, type=type, url=url, key=key, 
-                                        slices=slices, researchers=researchers)
+                                        slices=slices, researchers=researchers, email=email, pis=pis)
         self.api.manager.Register(self.api, record_dict)         
 
 
@@ -134,7 +153,7 @@ class RegistryCommands(Commands):
                pis='', researchers=''):
         """Update an existing Registry record""" 
         record_dict = self._record_dict(xrn=xrn, type=type, url=url, description=description, 
-                                        key=key, slices=slices, researchers=researchers)
+                                        key=key, slices=slices, researchers=researchers, pis=pis)
         self.api.manager.Update(self.api, record_dict)
         
     @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn (mandatory)') 
@@ -158,11 +177,17 @@ class RegistryCommands(Commands):
         from sfa.importer import Importer
         importer = Importer()
         importer.run()
+
+    def sync_db(self):
+        """Initialize or upgrade the db"""
+        from sfa.storage.dbschema import DBSchema
+        dbschema=DBSchema()
+        dbschema.init_or_upgrade
     
     @args('-a', '--all', dest='all', metavar='<all>', action='store_true', default=False,
-          help='Remove all registry records and all files in %s area' % Hierarchy().basedir)
+          help='Remove all registry records and all files in %s area' % help_basedir)
     @args('-c', '--certs', dest='certs', metavar='<certs>', action='store_true', default=False,
-          help='Remove all cached certs/gids found in %s' % Hierarchy().basedir )
+          help='Remove all cached certs/gids found in %s' % help_basedir )
     @args('-0', '--no-reinit', dest='reinit', metavar='<reinit>', action='store_false', default=True,
           help='Prevents new DB schema from being installed after cleanup')
     def nuke(self, all=False, certs=False, reinit=True):
@@ -274,7 +299,8 @@ class AggregateCommands(Commands):
 or the resources allocated by a slice"""  
         options = {'geni_rspec_version': rspec_version}
         if xrn:
-            options['geni_slice_urn'] = xrn
+            options['geni_slice_urn'] = Xrn(xrn, 'slice').get_urn()
+        print options
         resources = self.api.manager.ListResources(self.api, [], options)
         print resources
         
@@ -335,15 +361,14 @@ class SfaAdmin:
                   'aggregate': AggregateCommands,
                   'slicemgr': SliceManagerCommands}
 
-    def find_category (self, string):
-        for (k,v) in SfaAdmin.CATEGORIES.items():
-            if k.startswith(string): return k
-        for (k,v) in SfaAdmin.CATEGORIES.items():
-            if k.find(string) >=1: return k
-        return None
+    # returns (name,class) or (None,None)
+    def find_category (self, input):
+        full_name=Candidates (SfaAdmin.CATEGORIES.keys()).only_match(input)
+        if not full_name: return (None,None)
+        return (full_name,SfaAdmin.CATEGORIES[full_name])
 
     def summary_usage (self, category=None):
-        print "Usage:", self.script_name + " category action [<options>]"
+        print "Usage:", self.script_name + " category command [<options>]"
         if category and category in SfaAdmin.CATEGORIES: 
             categories=[category]
         else:
@@ -360,7 +385,9 @@ class SfaAdmin:
                 format="%%-%ds"%margin
                 print "%-15s"%name,
                 doc=getattr(method,'__doc__',None)
-                if not doc: print "<missing __doc__>"
+                if not doc: 
+                    print "<missing __doc__>"
+                    continue
                 lines=[line.strip() for line in doc.split("\n")]
                 line1=lines.pop(0)
                 print line1
@@ -375,33 +402,32 @@ class SfaAdmin:
             self.summary_usage()
 
         # ensure category is valid
-        category_str = argv.pop(0)
-        category=self.find_category (category_str)
-        if not category:
-            self.summary_usage()
+        category_input = argv.pop(0)
+        (category_name, category_class) = self.find_category (category_input)
+        if not category_name or not category_class:
+            self.summary_usage(category_name)
 
-        usage = "%%prog %s action [options]" % (category)
+        usage = "%%prog %s command [options]" % (category_name)
         parser = OptionParser(usage=usage)
-        command_class =  SfaAdmin.CATEGORIES.get(category, None)
-        if not command_class:
-            self.summary_usage(category)
     
         # ensure command is valid      
-        command_instance = command_class()
-        actions = command_instance._get_commands()
+        category_instance = category_class()
+        commands = category_instance._get_commands()
         if len(argv) < 1:
-            action = '__call__'
+            # xxx what is this about ?
+            command_name = '__call__'
         else:
-            action = argv.pop(0)
+            command_input = argv.pop(0)
+            command_name = Candidates (commands).only_match (command_input)
     
-        if hasattr(command_instance, action):
-            command = getattr(command_instance, action)
+        if command_name and hasattr(category_instance, command_name):
+            command = getattr(category_instance, command_name)
         else:
-            self.summary_usage(category)
+            self.summary_usage(category_name)
 
         # ensure options are valid
         options = getattr(command, 'options', [])
-        usage = "%%prog %s %s [options]" % (category, action)
+        usage = "%%prog %s %s [options]" % (category_name, command_name)
         parser = OptionParser(usage=usage)
         for arg, kwd in options:
             parser.add_option(*arg, **kwd)
@@ -415,14 +441,17 @@ class SfaAdmin:
 
         # execute command
         try:
-    #        print "invoking %s *=%s **=%s"%(command.__name__,cmd_args, cmd_kwds)
+            #print "invoking %s *=%s **=%s"%(command.__name__,cmd_args, cmd_kwds)
             command(*cmd_args, **cmd_kwds)
             sys.exit(0)
         except TypeError:
             print "Possible wrong number of arguments supplied"
+            #import traceback
+            #traceback.print_exc()
             print command.__doc__
             parser.print_help()
             #raise
         except Exception:
             print "Command failed, please check log for more info"
             raise
+