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