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