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