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