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