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