use command instead of action
[sfa.git] / sfa / client / sfaadmin.py
1 #!/usr/bin/python
2 import os
3 import sys
4 import copy
5 from pprint import pformat, PrettyPrinter
6 from optparse import OptionParser
7
8 from sfa.generic import Generic
9 from sfa.util.xrn import Xrn
10 from sfa.storage.record import Record 
11 from sfa.client.sfi import save_records_to_file
12 from sfa.trust.hierarchy import Hierarchy
13 from sfa.trust.gid import GID
14
15 pprinter = PrettyPrinter(indent=4)
16
17 try:
18     help_basedir=Hierarchy().basedir
19 except:
20     help_basedir='*unable to locate Hierarchy().basedir'
21
22 def optparse_listvalue_callback(option, opt, value, parser):
23     setattr(parser.values, option.dest, value.split(','))
24
25 def args(*args, **kwargs):
26     def _decorator(func):
27         func.__dict__.setdefault('options', []).insert(0, (args, kwargs))
28         return func
29     return _decorator
30
31 ### utility to match command-line args to names
32 class Candidates:
33     def __init__ (self, names):
34         self.names=names
35     # is an input string acceptable for one of the known names?
36     @staticmethod
37     def fits (input, name):
38         return name.find(input)==0
39     # returns one of the names if the input name has a unique match
40     # or None otherwise
41     def only_match (self, input):
42         matches=[ name for name in self.names if Candidates.fits(input,name) ]
43         if len(matches)==1: return matches[0]
44         else: return None
45
46 class Commands(object):
47     def _get_commands(self):
48         command_names = []
49         for attrib in dir(self):
50             if callable(getattr(self, attrib)) and not attrib.startswith('_'):
51                 command_names.append(attrib)
52         return command_names
53
54
55 class RegistryCommands(Commands):
56     def __init__(self, *args, **kwds):
57         self.api= Generic.the_flavour().make_api(interface='registry')
58  
59     def version(self):
60         """Display the Registry version""" 
61         version = self.api.manager.GetVersion(self.api, {})
62         pprinter.pprint(version)
63
64     @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='authority to list (hrn/urn - mandatory)') 
65     @args('-t', '--type', dest='type', metavar='<type>', help='object type', default=None) 
66     @args('-r', '--recursive', dest='recursive', metavar='<recursive>', help='list all child records', 
67           action='store_true', default=False) 
68     def list(self, xrn, type=None, recursive=False):
69         """List names registered at a given authority - possibly filtered by type"""
70         xrn = Xrn(xrn, type) 
71         options = {'recursive': recursive}    
72         records = self.api.manager.List(self.api, xrn.get_hrn(), options=options)
73         for record in records:
74             if not type or record['type'] == type:
75                 print "%s (%s)" % (record['hrn'], record['type'])
76
77
78     @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn (mandatory)') 
79     @args('-t', '--type', dest='type', metavar='<type>', help='object type', default=None) 
80     @args('-o', '--outfile', dest='outfile', metavar='<outfile>', help='save record to file') 
81     @args('-f', '--format', dest='format', metavar='<display>', type='choice', 
82           choices=('text', 'xml', 'simple'), help='display record in different formats') 
83     def show(self, xrn, type=None, format=None, outfile=None):
84         """Display details for a registered object"""
85         records = self.api.manager.Resolve(self.api, xrn, type, True)
86         for record in records:
87             sfa_record = Record(dict=record)
88             sfa_record.dump(format) 
89         if outfile:
90             save_records_to_file(outfile, records)  
91
92
93     def _record_dict(self, xrn=None, type=None, 
94                      url=None, description=None, email='', 
95                      key=None, 
96                      slices=[], researchers=[], pis=[]):
97         record_dict = {}
98         if xrn:
99             if type:
100                 xrn = Xrn(xrn, type)
101             else:
102                 xrn = Xrn(xrn)
103             record_dict['urn'] = xrn.get_urn()
104             record_dict['hrn'] = xrn.get_hrn()
105             record_dict['type'] = xrn.get_type()
106         if url:
107             record_dict['url'] = url
108         if description:
109             record_dict['description'] = description
110         if key:
111             try:
112                 pubkey = open(key, 'r').read()
113             except IOError:
114                 pubkey = key
115             record_dict['keys'] = [pubkey]
116         if slices:
117             record_dict['slices'] = slices
118         if researchers:
119             record_dict['researcher'] = researchers
120         if email:
121             record_dict['email'] = email
122         if pis:
123             record_dict['pi'] = pis
124         return record_dict
125
126     @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn (mandatory)') 
127     @args('-t', '--type', dest='type', metavar='<type>', help='object type', default=None) 
128     @args('-e', '--email', dest='email', default="",
129           help="email (mandatory for users)")
130     @args('-u', '--url', dest='url', metavar='<url>', default=None,
131           help="URL, useful for slices")
132     @args('-d', '--description', dest='description', metavar='<description>', 
133           help='Description, useful for slices', default=None)
134     @args('-k', '--key', dest='key', metavar='<key>', help='public key string or file', 
135           default=None)
136     @args('-s', '--slices', dest='slices', metavar='<slices>', help='slice xrns', 
137           default='', type="str", action='callback', callback=optparse_listvalue_callback)
138     @args('-r', '--researchers', dest='researchers', metavar='<researchers>', help='slice researchers', 
139           default='', type="str", action='callback', callback=optparse_listvalue_callback)
140     @args('-p', '--pis', dest='pis', metavar='<PIs>', 
141           help='Principal Investigators/Project Managers ', 
142           default='', type="str", action='callback', callback=optparse_listvalue_callback)
143     def register(self, xrn, type=None, url=None, description=None, key=None, slices='', 
144                  pis='', researchers='',email=''):
145         """Create a new Registry record"""
146         record_dict = self._record_dict(xrn=xrn, type=type, url=url, key=key, 
147                                         slices=slices, researchers=researchers, email=email, pis=pis)
148         self.api.manager.Register(self.api, record_dict)         
149
150
151     @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn (mandatory)')
152     @args('-t', '--type', dest='type', metavar='<type>', help='object type', default=None)
153     @args('-u', '--url', dest='url', metavar='<url>', help='URL', default=None)
154     @args('-d', '--description', dest='description', metavar='<description>',
155           help='Description', default=None)
156     @args('-k', '--key', dest='key', metavar='<key>', help='public key string or file',
157           default=None)
158     @args('-s', '--slices', dest='slices', metavar='<slices>', help='slice xrns',
159           default='', type="str", action='callback', callback=optparse_listvalue_callback)
160     @args('-r', '--researchers', dest='researchers', metavar='<researchers>', help='slice researchers',
161           default='', type="str", action='callback', callback=optparse_listvalue_callback)
162     @args('-p', '--pis', dest='pis', metavar='<PIs>',
163           help='Principal Investigators/Project Managers ',
164           default='', type="str", action='callback', callback=optparse_listvalue_callback)
165     def update(self, xrn, type=None, url=None, description=None, key=None, slices='', 
166                pis='', researchers=''):
167         """Update an existing Registry record""" 
168         record_dict = self._record_dict(xrn=xrn, type=type, url=url, description=description, 
169                                         key=key, slices=slices, researchers=researchers, pis=pis)
170         self.api.manager.Update(self.api, record_dict)
171         
172     @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn (mandatory)') 
173     @args('-t', '--type', dest='type', metavar='<type>', help='object type', default=None) 
174     def remove(self, xrn, type=None):
175         """Remove given object from the registry"""
176         xrn = Xrn(xrn, type)
177         self.api.manager.Remove(self.api, xrn)            
178
179
180     @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn (mandatory)') 
181     @args('-t', '--type', dest='type', metavar='<type>', help='object type', default=None) 
182     def credential(self, xrn, type=None):
183         """Invoke GetCredential"""
184         cred = self.api.manager.GetCredential(self.api, xrn, type, self.api.hrn)
185         print cred
186    
187
188     def import_registry(self):
189         """Run the importer"""
190         from sfa.importer import Importer
191         importer = Importer()
192         importer.run()
193     
194     @args('-a', '--all', dest='all', metavar='<all>', action='store_true', default=False,
195           help='Remove all registry records and all files in %s area' % help_basedir)
196     @args('-c', '--certs', dest='certs', metavar='<certs>', action='store_true', default=False,
197           help='Remove all cached certs/gids found in %s' % help_basedir )
198     @args('-0', '--no-reinit', dest='reinit', metavar='<reinit>', action='store_false', default=True,
199           help='Prevents new DB schema from being installed after cleanup')
200     def nuke(self, all=False, certs=False, reinit=True):
201         """Cleanup local registry DB, plus various additional filesystem cleanups optionally"""
202         from sfa.storage.dbschema import DBSchema
203         from sfa.util.sfalogging import _SfaLogger
204         logger = _SfaLogger(logfile='/var/log/sfa_import.log', loggername='importlog')
205         logger.setLevelFromOptVerbose(self.api.config.SFA_API_LOGLEVEL)
206         logger.info("Purging SFA records from database")
207         dbschema=DBSchema()
208         dbschema.nuke()
209
210         # for convenience we re-create the schema here, so there's no need for an explicit
211         # service sfa restart
212         # however in some (upgrade) scenarios this might be wrong
213         if reinit:
214             logger.info("re-creating empty schema")
215             dbschema.init_or_upgrade()
216
217         # remove the server certificate and all gids found in /var/lib/sfa/authorities
218         if certs:
219             logger.info("Purging cached certificates")
220             for (dir, _, files) in os.walk('/var/lib/sfa/authorities'):
221                 for file in files:
222                     if file.endswith('.gid') or file == 'server.cert':
223                         path=dir+os.sep+file
224                         os.unlink(path)
225
226         # just remove all files that do not match 'server.key' or 'server.cert'
227         if all:
228             logger.info("Purging registry filesystem cache")
229             preserved_files = [ 'server.key', 'server.cert']
230             for (dir,_,files) in os.walk(Hierarchy().basedir):
231                 for file in files:
232                     if file in preserved_files: continue
233                     path=dir+os.sep+file
234                     os.unlink(path)
235         
236     
237 class CertCommands(Commands):
238     
239     def import_gid(self, xrn):
240         pass
241
242     @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn (mandatory)')
243     @args('-t', '--type', dest='type', metavar='<type>', help='object type', default=None)
244     @args('-o', '--outfile', dest='outfile', metavar='<outfile>', help='output file', default=None)
245     def export(self, xrn, type=None, outfile=None):
246         """Fetch an object's GID from the Registry"""  
247         from sfa.storage.alchemy import dbsession
248         from sfa.storage.model import RegRecord
249         hrn = Xrn(xrn).get_hrn()
250         request=dbsession.query(RegRecord).filter_by(hrn=hrn)
251         if type: request = request.filter_by(type=type)
252         record=request.first()
253         if record:
254             gid = GID(string=record.gid)
255         else:
256             # check the authorities hierarchy
257             hierarchy = Hierarchy()
258             try:
259                 auth_info = hierarchy.get_auth_info(hrn)
260                 gid = auth_info.gid_object
261             except:
262                 print "Record: %s not found" % hrn
263                 sys.exit(1)
264         # save to file
265         if not outfile:
266             outfile = os.path.abspath('./%s.gid' % gid.get_hrn())
267         gid.save_to_file(outfile, save_parents=True)
268         
269     @args('-g', '--gidfile', dest='gid', metavar='<gid>', help='path of gid file to display (mandatory)') 
270     def display(self, gidfile):
271         """Print contents of a GID file"""
272         gid_path = os.path.abspath(gidfile)
273         if not gid_path or not os.path.isfile(gid_path):
274             print "No such gid file: %s" % gidfile
275             sys.exit(1)
276         gid = GID(filename=gid_path)
277         gid.dump(dump_parents=True)
278     
279
280 class AggregateCommands(Commands):
281
282     def __init__(self, *args, **kwds):
283         self.api= Generic.the_flavour().make_api(interface='aggregate')
284    
285     def version(self):
286         """Display the Aggregate version"""
287         version = self.api.manager.GetVersion(self.api, {})
288         pprinter.pprint(version)
289
290     def slices(self):
291         """List the running slices at this Aggregate"""
292         print self.api.manager.ListSlices(self.api, [], {})
293
294     @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn (mandatory)') 
295     def status(self, xrn):
296         """Display the status of a slice or slivers"""
297         urn = Xrn(xrn, 'slice').get_urn()
298         status = self.api.manager.SliverStatus(self.api, urn, [], {})
299         pprinter.pprint(status)
300  
301     @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn', default=None)
302     @args('-r', '--rspec-version', dest='rspec_version', metavar='<rspec_version>', 
303           default='GENI', help='version/format of the resulting rspec response')  
304     def resources(self, xrn=None, rspec_version='GENI'):
305         """Display the available resources at an aggregate 
306 or the resources allocated by a slice"""  
307         options = {'geni_rspec_version': rspec_version}
308         if xrn:
309             options['geni_slice_urn'] = Xrn(xrn, 'slice').get_urn()
310         print options
311         resources = self.api.manager.ListResources(self.api, [], options)
312         print resources
313         
314     @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='slice hrn/urn (mandatory)')
315     @args('-r', '--rspec', dest='rspec', metavar='<rspec>', help='rspec file (mandatory)')  
316     @args('-u', '--user', dest='user', metavar='<user>', help='hrn/urn of slice user (mandatory)')  
317     @args('-k', '--key', dest='key', metavar='<key>', help="path to user's public key file (mandatory)")  
318     def create(self, xrn, rspec, user, key):
319         """Allocate slivers"""
320         xrn = Xrn(xrn, 'slice')
321         slice_urn=xrn.get_urn()
322         rspec_string = open(rspec).read()
323         user_xrn = Xrn(user, 'user')
324         user_urn = user_xrn.get_urn()
325         user_key_string = open(key).read()
326         users = [{'urn': user_urn, 'keys': [user_key_string]}]
327         options={}
328         self.api.manager.CreateSliver(self, slice_urn, [], rspec_string, users, options) 
329
330     @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='slice hrn/urn (mandatory)')
331     def delete(self, xrn):
332         """Delete slivers""" 
333         self.api.manager.DeleteSliver(self.api, xrn, [], {})
334  
335     @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='slice hrn/urn (mandatory)')
336     def start(self, xrn):
337         """Start slivers"""
338         self.api.manager.start_slice(self.api, xrn, [])
339
340     @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='slice hrn/urn (mandatory)')
341     def stop(self, xrn):
342         """Stop slivers"""
343         self.api.manager.stop_slice(self.api, xrn, [])      
344
345     @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='slice hrn/urn (mandatory)')
346     def reset(self, xrn):
347         """Reset sliver"""
348         self.api.manager.reset_slice(self.api, xrn)
349
350
351 #    @args('-x', '--xrn', dest='xrn', metavar='<xrn>', help='object hrn/urn', default=None)
352 #    @args('-r', '--rspec', dest='rspec', metavar='<rspec>', help='request rspec', default=None)
353 #    def ticket(self, xrn, rspec):
354 #        pass
355
356
357
358 class SliceManagerCommands(AggregateCommands):
359     
360     def __init__(self, *args, **kwds):
361         self.api= Generic.the_flavour().make_api(interface='slicemgr')
362
363
364 class SfaAdmin:
365
366     CATEGORIES = {'certificate': CertCommands,
367                   'registry': RegistryCommands,
368                   'aggregate': AggregateCommands,
369                   'slicemgr': SliceManagerCommands}
370
371     # returns (name,class) or (None,None)
372     def find_category (self, input):
373         full_name=Candidates (SfaAdmin.CATEGORIES.keys()).only_match(input)
374         if not full_name: return (None,None)
375         return (full_name,SfaAdmin.CATEGORIES[full_name])
376
377     def summary_usage (self, category=None):
378         print "Usage:", self.script_name + " category command [<options>]"
379         if category and category in SfaAdmin.CATEGORIES: 
380             categories=[category]
381         else:
382             categories=SfaAdmin.CATEGORIES
383         for c in categories:
384             cls=SfaAdmin.CATEGORIES[c]
385             print "==================== category=%s"%c
386             names=cls.__dict__.keys()
387             names.sort()
388             for name in names:
389                 method=cls.__dict__[name]
390                 if name.startswith('_'): continue
391                 margin=15
392                 format="%%-%ds"%margin
393                 print "%-15s"%name,
394                 doc=getattr(method,'__doc__',None)
395                 if not doc: 
396                     print "<missing __doc__>"
397                     continue
398                 lines=[line.strip() for line in doc.split("\n")]
399                 line1=lines.pop(0)
400                 print line1
401                 for extra_line in lines: print margin*" ",extra_line
402         sys.exit(2)
403
404     def main(self):
405         argv = copy.deepcopy(sys.argv)
406         self.script_name = argv.pop(0)
407         # ensure category is specified    
408         if len(argv) < 1:
409             self.summary_usage()
410
411         # ensure category is valid
412         category_input = argv.pop(0)
413         (category_name, category_class) = self.find_category (category_input)
414         if not category_name or not category_class:
415             self.summary_usage(category_name)
416
417         usage = "%%prog %s command [options]" % (category_name)
418         parser = OptionParser(usage=usage)
419     
420         # ensure command is valid      
421         category_instance = category_class()
422         commands = category_instance._get_commands()
423         if len(argv) < 1:
424             # xxx what is this about ?
425             command_name = '__call__'
426         else:
427             command_input = argv.pop(0)
428             command_name = Candidates (commands).only_match (command_input)
429     
430         if command_name and hasattr(category_instance, command_name):
431             command = getattr(category_instance, command_name)
432         else:
433             self.summary_usage(category_name)
434
435         # ensure options are valid
436         options = getattr(command, 'options', [])
437         usage = "%%prog %s %s [options]" % (category_name, command_name)
438         parser = OptionParser(usage=usage)
439         for arg, kwd in options:
440             parser.add_option(*arg, **kwd)
441         (opts, cmd_args) = parser.parse_args(argv)
442         cmd_kwds = vars(opts)
443
444         # dont overrride meth
445         for k, v in cmd_kwds.items():
446             if v is None:
447                 del cmd_kwds[k]
448
449         # execute command
450         try:
451             #print "invoking %s *=%s **=%s"%(command.__name__,cmd_args, cmd_kwds)
452             command(*cmd_args, **cmd_kwds)
453             sys.exit(0)
454         except TypeError:
455             print "Possible wrong number of arguments supplied"
456             #import traceback
457             #traceback.print_exc()
458             print command.__doc__
459             parser.print_help()
460             #raise
461         except Exception:
462             print "Command failed, please check log for more info"
463             raise
464
465 candidates_specs=[
466 ('create delete reset resources slices start status stop version', 
467   [ ('ver','version'),
468     ('r',None),
469     ('re',None),
470     ('res',None),
471     ('rese','reset'),
472     ('reset','reset'),
473     ('reso','resources'),
474     ('sli','slices'),
475     ('st',None),
476     ('sta',None),
477     ('stop','stop'),
478     ('a',None),
479 ])
480 ]
481
482 def test_candidates ():
483     for (names, tuples) in candidates_specs:
484         names=names.split()
485         for (input,expected) in tuples:
486             got=Candidates(names).only_match(input)
487             if got==expected: print '.',
488             else: print 'X FAIL','names[',names,'] input',input,'expected',expected,'got',got
489
490 if __name__ == '__main__':
491     test_candidates()