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