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